Java. Exceptions. Keywords try, catch, finally. Examples

Exceptions. Keywords try, catch, finally. Examples


Contents



1. What is an exceptional situation?

An exceptional situation is a program error that occurs during the execution of a sequence of program code. A program error may be a logical error of a programmer during program development. For example, an exceptional situation may occur in the case of:

  • division by zero
  • attempts to access an array element whose index number is outside the declared one;
  • attempts to take the root of a negative number;
  • attempts to open a file by name that is not on the disk;
  • other cases.

Proper exception handling is an important in writing professional Java programs.

 

2. The concept of exceptions in the Java language

As a rule, each exception can have its own error code and processing of this code (displaying of the corresponding messages, etc.). The Java programming language was developed mechanism for handling exceptions.

In the Java programming language, an exception is a special object that describes an exceptional situation that has arisen in some part of the program code. The object representing the exception is generated when the exception occurs. After the occurrence of a critical (exceptional) situation, an exception is caught and processed. Thus, the notion of generating an exception arises. Generating an exception is the process of creating an object that describes the exception.

 

3. What ways can exceptions be generated?

In Java, exceptions can be generated in one of two ways:

  • automatically. In this case, exceptions are generated by the Java runtime. These exceptions include errors that understand the rules of the Java language or restrictions imposed by the system;
  • manually. In this case, exceptions are generated in the program code that is being developed. Manual exceptions are programmed to notify the calling code of possible errors in the methods of the program being developed.

 

4. When is the standard Java exception handler called?

The standard Java exception handler is called when the program:

  • does not use the try…catch block to handle and catch the exception at all;
  • contains a try…catch block, but this type of exception is not caught in this block.

If the program contains its own try…catch code to handle this exception, then the standard exception handler is not called.

 

5. What keywords are used to handle exceptions in Java?

The following keywords are used to handle exceptions in Java:

  • try;
  • catch;
  • throw;
  • throws;
  • finally.

 

6. What is the purpose of the try…catch… finally statement? General form

In Java, you can manually catch exceptions and handle them accordingly. It is important that when an exception occurs, the program does not stop its execution.

To track, generate, and handle exceptions in the Java programming language, use the try…catch…finally construct, which has the following general form

try {
    // block of code in which exceptions are tracked and generated
    // ...
}
catch (type_exception_1 objEx1) {
    // exception handler of type_exception_1 type
    // ...
}
catch (type_exception_2 objEx2) {
    // exception handler of type_exception_2 type
    // ...
}
...
catch (type_exception_N objEx) {
    // exception handler of type_exception_N type
    // ...
}
finally {
    // block of code that must be executed after the try block is completed
    // ...
}

The try block contains program statements that need to be monitored and, in the event of an exception, an exception is thrown. Inside the try block, various methods can be called that can generate an exception. However, there will be only one exception handler.

The catch block contains the program code that handles the intercepted exception (exception handler). The code in the catch block implements the execution of the appropriate actions when an exception occurred in the try block. There can be several catch blocks. If an exception is thrown, the exception engine looks for the first exception handler whose argument matches the current type of exception. After that, it is included in the catch block, and, as a result, the exception is considered processed. Only one matching catch block is processed.

The finally block indicates the code that must be executed after the completion of the try block. The block of finally statements is executed regardless of whether an exception is generated or not. If an exception is thrown, the block of finally statements is executed even if none of the catch statements matches this exception.

The try and catch statements are one. The finally operator may be missing.

 

7. An example of generating an exception and its interception by the standard Java exception handler

If the program does not have its own try…catch block to catch the exception, the standard exception handler will be called. The example demonstrates calling the standard handler.

The DemoExceptions class is declared. For the purpose of demonstration, the method DivNumbers() is declared in the class. The method returns a double number, which is the result of dividing two integer values of the variables a and b. These variables are the input parameters of the method.

If b = 0, then when dividing a by b, a “division by zero” exception of type ArithmeticException may occur. There is no code in the program that explicitly intercepts and handles this situation. Therefore, the standard Java handler is called.

The text of the DemoExceptions class is as follows:

// class that implements the method
// in which an exception may occur
class DemoExceptions {

    // method in which division by 0 can occur
    double DivNumbers(int a, int b) {
        // when divided by 0, the standard java handler will be called
        double res;
        res = a/b;
        return res;
    }
}

If in another class to use the DivNumbers() method as follows

public class Train01 {

    public static void main(String[] args) {
        DemoExceptions d = new DemoExceptions(); // create an class instance
        double res;

        // invoke the DivNumbers() method
        res = d.DivNumbers(2, 0); // 2/0 => division by 0
        System.out.println("res = " + res);
    }
}

then will be called standard java handler which will output the following message

Exception in thread "main" java.lang.ArithmeticException: / by zero
at DemoExceptions.DivNumbers(Train01.java:10)
at Train01.main(Train01.java:82)

The message indicates the type of class ArithmeticException. This is a subclass derived from the RunTimeException class. This subclass describes the arithmetic errors “division by 0”, “taking the root of a negative number”, etc.

 

8. Example of catching and handling exceptions using the try … catch statement

The example implements the DemoExceptions class, which declares a method named DivNumbers2().The DivNumbers2() method divides the input parameter a into the input parameter b. The DivNumbers2() method demonstrates catching a dividing by zero exception using a try…catch block.

The text of DemoExceptions class is as follows

// class that implements the method
// in which an exception may occur
class DemoExceptions {
    // the method in which the division by 0 is processed,
    // the try..catch statement
    double DivNumbers2(int a, int b) {
        double res=0; // The variable res must be initialized.
        try {
            res = a/b; // if b=0, then an exception is generated
        }
        catch (ArithmeticException e) {
            System.out.println("Division by 0.");
        }
        return res;
    }
}

Now, when using the DivNumbers2() method in another class

public class Train01 {

    public static void main(String[] args) {
        // create an instance of class
        DemoExceptions d = new DemoExceptions();
        double res;

        // invoke the DivNumbers2() method
        res = d.DivNumbers2(2, 0); // 2/0 => division by 0
        System.out.println("res = " + res);
    }
}

the system will issue the following result after running the program for execution

Division by 0.
res = 0.0

As can be seen from the above code, the DivNumbers2() method will call its own handler, which is implemented in the try…catch statement. The try block contains the program code that needs to be checked.

...
res = a/b;
...

If an exception occurs (b = 0), then control is immediately passed from the try block to the catch block. In the catch block, the exception is processed and the corresponding message is displayed.

...
catch (ArithmeticException e) {
    System.out.println("Division by 0.");
}
...

So, if b = 0:

  • an exception of type ArithmeticException is generated;
  • transition to exception handling (catch block);
  • in the catch block, a corresponding message is displayed;
  • after the catch block, the program execution does not stop. As a result, the variable res gets the value 0.

You can change the output of your own exception message to a standard message. In this case, you need to change the text in the catch block to the following

...
catch (ArithmeticException e) {
    System.out.println(e);
    //System.out.println("Division by 0.");
}
...

After the changes, the result of the program will be as follows

java.lang.ArithmeticException: / by zero
res = 0.0

 

9. An example of catching and handling exceptions with a try…catch…finally block. Demonstration of the finally statement

The example continues the development of the two preceding items 7, 8. The example demonstrates the purpose of the finally block in the try…catch…finally statement.

The DemoExceptions class is declared. Interception of a dividing by 0 exception is demonstrated in the class. This interception is implemented in the DivNumbers3() method. To catch and handle an exception, the DivNumbers3() method uses a try…catch…finally statement.

The text of DemoExceptions class is as follows

// a class that implements a method
// in which an exception may occur
class DemoExceptions {

    // the method in which the division by 0 is processed,
    // the try..catch..finally statement
    double DivNumbers3(int a, int b) {
        double res; // it is not necessary to initialize because there is a finally block
        try {
            res = a/b;
        }
        catch (ArithmeticException e) {
            System.out.println("Division by 0.");
        }
        finally {
            res = 0; // necessarily will be called
        }
        return res;
    }
}

In the DivNumbers3() method, the variable res is declared, which is the result of dividing a by b. Since the try … catch statement contains a finally part, the line

...
finally {
    res = 0; // necessarily will be called
}
...

will always be called. And before the operator

...
return res;
...

The variable res will always be initialized. Therefore, the Java compiler does not require initialization of the variable at the beginning of the code. As you know, in order to return a variable value with a return statement, this variable must be initialized. So, the finally block is always called.

Using the DivNumbers3() method in another class may be as follows

public class Train01 {

    public static void main(String[] args) {
        DemoExceptions d = new DemoExceptions();
        double res;
        res = d.DivNumbers3(2, 0); // 2/0 => division by zero
        System.out.println("res = " + res);
    }
}

The result of the program

Division by 0.
res = 0.0

 

10. How to implement the output of description of the exception? Example

If you want to display the description of the exception e, you can change the output in the catch handler as follows (see p. 8)

...
catch (ArithmeticException e) {
    // catch the division error by 0
    System.out.println("Exception: " + e);
}
...

As a result, the program will display the following result.

Exception: java.lang.ArithmeticException: / by zero

 

11. Example of intercepting several exceptions (several catch statements)

There are cases when several exceptions can occur in a single code fragment. To handle several exceptions in the try… catch block, you can use several catch statements. Each catch statement is used to catch a separate type of exception.

The implementation of the class DivArrays is as follows

// several catch statements
// class that divides element by element in arrays
class DivArrays {
    double[] A1;
    double[] A2;

    // class constructor
    DivArrays(int n1, double[] _A1, int n2, double[] _A2) {
        // create an arrays
        A1 = new double[n1];
        for (int i=0; i<n1; i++)
            A1[i] = _A1[i];

        A2 = new double[n2];
        for (int i=0; i<n2; i++)
            A2[i] = _A2[i];
    }

    // a method that divides an array of elements A1 into an array of A2
    // method returns an array of type double
    double[] Division() {
        double[] A3;
        int n3;

        // set the largest of the sizes
        if (A1.length > A2.length)
            n3 = A1.length;
        else
            n3 = A2.length;

        A3 = new double[n3];

        // loop by i, the loop handles the exception
        for (int i=0; i<n3; i++) {
            try {
                // throw an exception if division by 0
                if (A2[i]==0.0)
                    throw new ArithmeticException();

                A3[i] = A1[i]/A2[i];
            }
            catch (ArithmeticException e) {
                // catch the division to 0
                A3[i] = 0; // simply set the value of A3 to 0
            }
            catch (ArrayIndexOutOfBoundsException e) {
                // catch when the index is out of bounds of the array
                // This is the case when arrays lengths differ
                A3[i] = -1;
            }
        }
        return A3;
    }
}

Using a class in another program code

public class Train03 {

    public static void main(String[] args) {
        double[] A1 = { 2.5, 2.0, 1.5, 0.5 };
        double[] A2 = { 1.0, 0.0, 2.0 };
        double[] A3;

        DivArrays dA = new DivArrays(4,A1,3,A2);

        A3 = dA.Division();

        // display the array d
        for (int i=0; i<A3.length; i++)
            System.out.println("A[" + i + "] = " + A3[i]);
    }
}

The result of the program

A[0] = 2.5
A[1] = 0.0
A[2] = 0.75
A[3] = -1.0

 


Related topics