Exception handling basics

Bug

One of the useful concepts that came with modern languages is exception handling. In a nutshell, it is the concept of catching exceptions as they occur, instead of checking the inputs and return values of every function called. Consider this simple example:

int divide(int a, int b) {
    if (b == 0) {
        // ...show an error message
    else {
        return a / b;
    }
}

Now, you should never show a message inside a function called divide, but for simplicity, please bear with me. Consider the following equivalent:

int divide(int a, int b) {
    try {
        return a / b;
    catch (ArithmeticException e) {
        // ...show an error message (division by zero) to the user...
    }
}

In the second example, you are not checking for the inputs because somebody else already does. The integer division operator (/) is programmed to throw ArithmeticException when the divisor is 0, so it is enough to ‘catch’ this exception instead.

While it is possible to catch every exception, it is not advised and considered to be an example of bad programming. For example, you can write

catch (Exception e) {
    // show a generic error message to the user...
}

to catch all exceptions, but in this case you may erroneously hide bugs in your code, or even problems which are not directly related to your code, such as an IOException.