Java

How to throw Exception in Java

An exception is a potential error, of which the Java system signals the Java program. If the exception (error) is not handled, the thread concerned will stop operating. If the program were single-threaded, then the program would stop operating. Consider the following program:

    public class TheClass {
        public static void main(String[] args) {
System.out.println("seen 1");
            int numerator  = 6;
            int denominator  = 0;
            int quotient = numerator / denominator;
System.out.println("seen 2");
System.out.println(quotient);
        }
    }

This program tries to divide by 0 at the fourth statement in the main() method. In mathematics, no number should be divided by 0. Computers also do not allow this. This program should print out “seen 1”, then if division by zero is possible by the computer, the program should print “seen 2” and then print the quotient of 6 divided by zero.

This program is compiled successfully by the javac compiler. However, when the program is run by the Java Virtual Machine (operating system), “seen 1” is printed, and the program stops at the fourth statement, where division by zero is expected, whence (where and then) an error message is issued (displayed). The program stops executing at the division statement by zero, prints an error message and stops operating. After that, the last two statements are not executed (do not operate).

However, if this were multiplication by zero, which is allowed, then the last two statements would have been executed. This article provides the basics of throwing and handling an exception in Java.

Handling Errors

With Java, it is possible to handle an error, like division by zero, with simple code; so that the statements (coding) after the error should operate (be executed). What is the error here? – The error here is division-by-zero. The code (solution) by the programmer should not allow the error to take place. The programmer has to code what is known as throwing the error, which is a new exception object. The exception object has to be caught. When the exception object is caught, the program has to recover from it. Recovering from an error means handling the exception.

The Exception library class handles the error more than the programmer. The Exception class does not have to be imported at the beginning of the program. This importation is done automatically, without the help of the programmer.

The Exception Class

There is two main error handling classes in Java: the Exception class and the Error class. This article deals only with the Exception class. As a character, the exception class knows ordinary errors, such as division-by-zero and unwanted null values in a literal string.

When a new exception object is thrown, just after the statement that would result in an error, the Exception class library would know the error; if it is an ordinary error. The Exception class does not have to be imported at the beginning of the program. This importation is done automatically, without the help of the programmer.

The Java try Statement

The try statement is a compound statement, consisting of the try-block and a catch-block. In simplified form, the syntax is:

            try {
                        //problem statement;
                        throw new Exception();
* statements if no error occurs *
            }
            catch (Exception e) {
System.out.println("Exception message: " + e.getMessage());
            }

try is a reserved word; catch is a reserved word. The try-block has the problem statement. A statement like,

int quotient = numerator / denominator;

is a problem statement. If the denominator is not zero, no error occurs. If the denominator is zero, that is an error. The throw statement would typically be,

throw new Exception();

This throw statement should come immediately after the problem statement. If an error occurs, the throw statement throws a new Exception object. Note the parentheses. If the denominator is 0, a new Exception object is thrown. Below the throw statement are other statements that would be executed if no error occurred.

The catch-block above has one statement. It can have more. The throw statement in the try block throws an Exception object, which is caught in the parentheses of the catch-block signature, for further processing within its block. This activity is similar to a method call, with an argument to be received by the parentheses of the method implementation for further processing in the block of the method.

Remember that the Exception object can recognize different types of ordinary errors and cope with them. The Exception object has the method, getMessage(). This method returns a message that the user may understand as the cause of the error. This method call is employed inside the catch-block.

The following program puts the try-compound statement into practice, with the above division-by-zero problem:

    public class TheClass {
        public static void main(String[] args) {
System.out.println("seen 1");
            int numerator = 6; int denominator = 0; int quotient;
            try {
                    if (denominator == 0) {
                        quotient = numerator / denominator;
                        throw new Exception();
                    }
                    else
                        quotient = numerator / denominator;
System.out.println("seen 2");
System.out.println(quotient);
            }
            catch (Exception e) {
System.out.println("Exception message: " + e.getMessage());
            }
System.out.println("Continues");
        }
    }

The try-block has an if-compound statement. The if-part would execute the problem statement when the denominator is zero. The else-part would execute the problem statement when no error would occur when the denominator is not zero. This means that the programmer has to guide to the employment of the exception handling scheme. And so, in this case, the problem statement has been typed twice: once in the if-part and once in the else-part. The problem statement is not preceded by int because the quotient has been declared before the try compound statement.

In the try-block, the throw statement is just below the problem statement in the if-part of the if-compound statement. It is not in the else-part of the if-compound statement. It does not have to be there because the else-part is for the situation when the denominator (operand) is not zero (has no problem).

Read through the above program. The numerator is 6. If the denominator were 2, the output would have been:

seen 1

seen 2

3

Continues

This means that the other part of the if-compound statement was executed, not the if-part of the if-compound statement. In fact, the if-part (code) of the if-compound statement was not executed because the denominator was not zero. The rest of the code in the try-block was executed. The rest of the code in the try-block is supposed to be executed.

When the denominator is 0, the program will produce the output:

seen 1
Exception message: / by zero

Continues

Only the code in the if-part of the try-block has been executed in this situation. This means the throw statement was executed. The else-part and the code below the if-compound statement have not been executed. They are not normally executed in this situation.

The catch-block is not executed when there is no problem. Now, the catch-block was executed. That is, the single statement code in the catch-block was executed. The new Exception object is thrown, was received as e. The getMessage() method of the object, e that knows the ordinary errors (including the division-by-zero error) returned the message, “/ by zero”.

With this error returned message, the user would know that a division-by-zero error occurred, and it was handled. Handling, here, means that the division-by-zero did not cause any harm to the program, and, though the rest of the code below the error point in the try-compound statement would not be executed, the code below the try-compound statement would be executed. If the handling scheme were not present, the program would have terminated, and any code below that would not have been in the try-compound statement would not have been executed.

Throwing Exception, by a Method

In Java, the throw-exception statement can throw an Exception in the try-block, as illustrated above. A method can also throw an exception, but with a different syntax, still related to the try-block. The core of the try-block code is now in the method body and not in the try-block. The following program repeats the above one, but with a method throwing the exception. The class with the method implementation is:

    class AClass {
        int mthd(int nume, int deno) throws Exception {
            int quoti = nume / deno;
            return quoti;
        }
    }

The principal code in the method here is the problem statement. The problem statement is no longer in the try-block (below). The problem statement has been typed once, here, and for the whole program (not typed twice). The throw expression is now different. It is,

throws Exception

prolonging the method signature on the right. “throw” here is “throws”, with an s. Exception, here, does not have the parentheses.

There is now no need for the if-compound statement in the whole program. The body of the method and the “throws Exception” serve the purpose of the semantics of the if-else compound statement. The main class becomes:

    public class TheClass {
        public static void main(String[] args) {
System.out.println("seen 1");
            int numerator = 6; int denominator = 0; int quotient;
            try {
AClasseObj = new AClass();
                quotient = eObj.mthd(numerator, denominator);
System.out.println("seen 2");
System.out.println(quotient);
            }
            catch (Exception e) {
System.out.println("Exception message: " + e.getMessage());
            }
System.out.println("Continues");
        }
    }

It still has the try-catch compound statement. However, the problem statement is not here and is not typed twice. The if-else compound statement is also not here. It is no longer needed anywhere in the program. The output with its error message is the same as before, i.e.

seen 1

Exception message: / by zero

Continues

The behavior of the complete program is as before.

The finally clause

The try statement has three clauses: the try clause, the catch clause, and the finally clause. There can be more than one catch clause – see later. The finally block comes at the end of the try-compound statement, and it is for the programmer to pass on a message to the user that the possible error was handled. Coding of the finally clause is optional. The following code illustrates a use of the finally clause for the above program:

System.out.println("seen 1");
            int numerator = 6; int denominator = 0; int quotient;
            try {
AClasseObj = new AClass();
                quotient = eObj.mthd(numerator, denominator);
System.out.println("seen 2");
System.out.println(quotient);
            }
            catch (Exception e) {
System.out.println("Exception message: " + e.getMessage());
            }
            finally {
System.out.println("Any error was handled.");

If the denominator is 2, the output would be:

seen 1

seen 2

3

Any error was handled.

Continues

If the denominator is 0, the output would be:

seen 1

Exception message: / by zero

Any error was handled.

Continues

The finally block is executed, whether or not an error occurred.

Conclusion

An exception is thrown, with the simple statement in the try block, possibly coded with an if-compound statement and the problem statement. An exception can still be thrown by a method in relation to the try-compound statement. This article has been the basics of throwing an exception in Java.

About the author

Chrysanthus Forcha

Discoverer of mathematics Integration from First Principles and related series. Master’s Degree in Technical Education, specializing in Electronics and Computer Software. BSc Electronics. I also have knowledge and experience at the Master’s level in Computing and Telecommunications. Out of 20,000 writers, I was the 37th best writer at devarticles.com. I have been working in these fields for more than 10 years.