Broad Network


Java Exception Basics

Java Basics – Part 17

Forward: Exceptional circumstances such as runtime errors in a program should be handled, otherwise your program will not give the right results. In this part of the series, I explain Java Exception Basics.

By: Chrysanthus Date Published: 2 Sep 2012

Introduction

This is part 17 of my series, Java Basics. Exceptional circumstances such as runtime errors in a program should be handled, otherwise your program will not give the right results. Java has an object called, Exceptions to handle exceptional circumstances. In this part of the series, I explain Java Exception Basics. The use of the Exception object is the recommended way to handle runtime errors.

Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.

Runtime Error Example
In one of the previous parts of the series, you came across the following code:

class Err
    {
        public static void main(String[] args)
            {
                int numerator = 8;
                int denominator = 2;

                if (denominator != 0 )
                    {
                        int answer = numerator/denominator;
                        System.out.println(answer);
                    }
                else
                    {
                        System.out.println("Division by zero is not allowed!");
                    }
            }
    }

This code basically divides two numbers. In life you cannot divide a number by zero. Assuming that the denominator is input by the user, he may input zero. The division (process) by zero should not be allowed.

Let us look at what is in the code: the first two statements in the main method block are initialization of integers. The division takes place in the if-block. The if-condition checks whether the denominator is zero. If it is not, the division takes place in the if-block. If it is, the else part of the if-construct displays an error message to the user. This code segment is OK, because if the denominator is zero, the if-block will not be executed and no division will take place. With the above code, the execution of the program continues after the if/else construct.

This if/else construct does the division and prevents runtime error from taking place. The if-block does the division; the if-condition checks if error would occur; if error would occur, the else block display an alert message and the if-block and division are not executed.

Basic Components of Exception
With exception handling, you have basically what is called the try/catch construct. The try block has an important expression, which is, throw. throw takes an argument. There is a block called the finally block that is related to the try/catch block, but I will not talk about that in this series.

In the above if/else construct, the code segment of interest, which is the segment required, is the if-block. This if-block is what does the division. With Exception handling that code segment of interest goes into the try-block; the error message code segment (else-block) or error handler code segment goes into the catch-block. The throw expression in the try-block calls the catch-block passing its argument to it. The catch construct is like a method. This is the basic syntax for exception handling,

    try
        {
            //statements of interest
            throw new ExceptionClassname();
        }
    catch (ExceptionClassname ExceptVar)
        {
            //handle the error with the ExceptVar variable of the parameter
        }

The argument for the throw expression does not go into parentheses. The catch-construct has a parameter. The argument for the throw expression must be of the same type (class) as the parameter of the catch construct. You are the one who decides on the object type of the parameter, which is the same as the instantiated object type of the argument. The argument of the throw expression actually instantiates an object of a class that you have defined or that already exists somewhere. You are the one who decides on the content of the class or on what existing class to choose. You take these decisions depending on the nature of the error and how you want to handle the error.

The catch-block should immediately follow the try-block in your typing, as in the above syntax.

The previous code (program) is re-written using the try/catch construct, preceded by an exception class as follows:

class ZeroException extends Exception
    {
        String message = "Division by zero is not allowed!";
    }

class Exception1
    {
        public static void main(String[] args)
            {
                int numerator = 8;
                int denominator = 0;

                try
                    {
                        if (denominator != 0 )
                            {
                                int answer = numerator/denominator;
                                System.out.println(answer);
                            }
                        else
                            {
                                throw new ZeroException();
                            }
                    }
                catch (ZeroException e)
                    {
                        System.out.println(e.message);
                    }

            }
    }

Read through the above code, if you have not already done so. In many cases, the try-block equivalently has an if-condition whose block will execute if the condition does not detect the error. If the condition detects the error, the if-block will not execute, and the else part will throw the exception; that is the else part will call the catch-block sending the argument of the throw expression to it. The catch block uses the argument to display an appropriate error message to the user. This is what happens in many cases. Errors are not usually handled in the real sense of the word; usually an error message is sent to the user; an if-construct in the try block prevents the error from actually occurring. After this execution, the program continues in sequence from the try/catch construct. Try the above code.

Now the try-block may actually have an if/else if/else construct with many throws. You can have more than one catch corresponding blocks in the code; However, I will not go into the details of that in this series.

The error message is typed in an independent class. The argument of the throw expression is the instantiation of this class; that is why it has the new operator. In the above example the class just has a string property with the error message. In the above example, the catch block just prints (displays) the error message, using the argument object received at the catch block (parentheses).

You begin typing the class in the normal way and follow that with the reserved phrase, “extends Exception”.

Exception Not Caught
It is possible for an exception not to be caught. This can happen if the type of object thrown is not the type of object to be received by the catch block. If an exception is not caught, the program may crash (stop functioning). If an exception is caught, the program usually continues to operate, without the execution of the code segment causing the exception. In some cases involving user input, the user may be asked re-input a different value, for the pertinent code segment to be executed.

There is more to exceptions than what I have given in this tutorial, but I will not go into those extra bits in this basic series.

Let us end here and continue in the next part of the series.

Chrys
NEXT

Related Articles

Java Course

Comments

Become the Writer's Fan
Send the Writer a Message