9 Exception and Error Handling — Java Programming
9.1 Introduction
In this chapter we will learn in detail what exceptions are and how to manage and handle them. We will go through the built in exceptions and will create our own exceptions.
9.1.1 Exception and Throwable
An exception is an abnormal condition that arises in a program at the time of execution. That is, an exception is a runtime error. Compile time errors are that which occur during compilation. Exceptions are part of inheritance hierarchy, Exception is an instance of Throwable class.
9.1.2 Error
This class describes internal errors, such as out of disk space etc., Objects of those cannot be thrown. These are used to give information about errors. Ex. Stack overflow
9.1.3 Runtime Exception
The problems that arise out of wrong logic are the exceptions inherited from the class. For example bad type conversion, array access out of limits, null pointer access etc., fall into this type,
Typical exception examples are: ArrayIndexOutofBoundException, NullPointerException and ArithmeticException
9.2 Catching Exceptions and handling them
When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error.
That method may choose to handle the exception itself, or will pass it on. In any way exception is caught and is processed. Exception thrown by Java relate to usual errors that violate the rules of the Java language or the constraints of the Java execution environment.
Manually generated exceptions are typically used to report some error to the caller of a method. Java exception handling is done through:
- try: Statement that should be mentioned for exceptions should be put in the try block, If the exception occurs in try block, then it is thrown.
- catch: The code can catch this thrown exception using catch and handles it.
- throw: To manually throw an exception we use this.
- throws: Any exception that is throw out of method must be specified by a throws clause.
- finally: Any code that must be executed before a method returns is put in the finally block
The general form of exception handling is:
try{ //block of code to monitor for errors } catch(ExceptionType1 ex1) { //exception handler for exceptiontype1 } catch(ExceptionType2 ex2) { //exception handler for exceptiontype2 } Finally { //block of code to be executed before try block ends }
9.2.1 try and catch
What happens if code for exception handling is not written?
Suppose a divide by zero error occurs. When java runtime system detects, the divide by zero, it constructs a new exception and then throws this exception. The program execution stops, because once an exception has been thrown, it must be caught by an exception handler and should be dealt with immediately, this exception is caught by java runtime system.
Program 9.1. Write a program to find the area of a circle
//areaCircle.java //click here for code import java.io.*; public class areacircle { public static void main (String args[]) { float r = 0.0f; float pi = 3.14f; float area = 0.0f; try { Console in = System.console (); String fmt = "%1$4s %2$10s %3$10s%n"; // Read line String radstring = in.readLine (fmt, "Enter", "radius : ", " "); r = Float.valueOf (radstring); } catch (Exception e) { System.out.println ("error" + e); System.exit (1); } area = pi * (float) Math.pow (r, 2.0f); System.out.println ("Aread:" + area); } }
//exampleZeroerror.java //click here for code class exampleZeroerror { public static void main (String args[]) { int d, a; try { d = 0; a = 3 / d; /* the following statement will not be executed beacuse d=0 and an exception is thrown */ System.out.println ("not executed"); } catch (ArithmeticException e) { System.out.println ("Division by zero"); } System.out.println ("After catch statement"); } } /* Output: Division by zero After catch statement */
Exception is raised in a=3/d statement and control transfers out of try block, into the catch block.
When we use multiple catch statements, the exception subclasses must come before any of their super classes.
Nesting of try is allowed. If an inner try statement does not have a catch handler for a particular exception, the next try statement’s catch handlers are inspected for a match. If no catch matches then, Java runtime will handle the exception.
9.2.2 throw
Till now we caught exceptions thrown by java run time system.
The general form of throw is
throw th;
Where th is either an object of type Throwable or a subclass of Throwable. There are two ways to obtain a Throwable objects:
- using a parameters into a catch clause, or
- creating one with the new operator.
The flow of execution stops immediately after the throw statement. The nearest try block is inspected to see if it has a catch statement that matches the type of exception. If a match is found control is transferred to that statement. If not, the next try is expected. If no matching catch is found, then the default exception handler halts the program and prints the stack trace.
Program 9.3 Write a program to demonstrate throw.
//throwExample.java //click here for code class throwExample{ static void proc(){ try{ throw new NullPointerException("demon"); //demon is the name of the exception object } catch(NullPointerException e){ System.out.println("caught inside proc()"); throw e; } } public static void main(String args[]){ try{ proc(); } catch(NullPointerException e){ System.out.println("caught again "+e); } } } /* Output: caught inside proc() caught again java.lang.NullPointerException: demo */
9.2.3 throws
If a method does not have a catch for a particular exception and if any other method calls it, then it should convey this information to the calling method so that the ceiling method will handle the exception properly. A thrown clause lists the types of exceptions that a method might throw. This is necessary for all exceptions, except those of type Error or RuntimeException, or any of their subclasses. All other exceptions that a method might throws clause. If they are not, then a complier error will result.
The general form is
type method-names(parameters)thrown exception list { Statements }
Program 9.4 Write a program to demonstrate throws
//throwsExample.java //Click here for code class throwsExample{ static void th() throws NullPointerException{ System.out.println("inside th()"); throw new NullPointerException("demon"); } public static void main(String args[]){ try{ th(); } catch(NullPointerException e){ System.out.println("caught"+e); } } } /* Output: inside th() caughtjava.lang.NullPointerException: demon */
9.2.4 finally
Finally clause is optional
Finally has a block of code that is executed after a try or catch block is computed and before any code following the try or catch block. Whether catch catches the exception or not finally is executed. This is advantageous for closing file handles and freeing up any resources. Each try should have at least one catch or try clause.
Program 9.5 Write a program to demonstrate finally
//finallyExample.java //Click here for code class finallyExample{ static void p1(){ try { System.out.println("inside p1 try block"); throw new NullPointerException("demo"); } finally{ System.out.println("in p1 finally block"); } } static void p2(){ try { System.out.println("inside p2 try block"); return; } finally { System.out.println("in p2 finally block"); } } static void p3() { try { System.out.println("in p3 try block"); } finally { System.out.println("in p3 finally block"); } } public static void main(String args[]){ try { p1(); } catch(Exception e){ System.out.println("Exception caught"); } p2(); p3(); } } /* Output: inside p1 try block in p1 finally block Exception caught inside p2 try block in p2 finally block in p3 try block in p3 finally block */
In program first p1 is called and try and finally are executed and Exception is caught. Then p2 and p3 are called.
9.3 Java built in exceptions
Some of the commonly used Java built in exception are:
1. ArithmeticException – Arithmetic error, like divide by zero
2. ArrayIndexOutOfBoundsException- Array index out of bounds
3. ArrayStoreException- Assignment to an array element of an incompatible type.
4. ClassCastException-invalid cast.
5. IllegalArgumentException- Illegal argument used to invoke a method.
6. IndexOutofBoundException – Some type of index is out of bounds.
7. NegativeArraySizeException- Array created with a negative size.
8. NullPointerException- Invalid se of null reference.
9. NumberFormatConversion- Invalid conversion of a string to numeric format.
10. StringIndexOutofBounds- Attempt to index outside the bounds of a string.
11. ClassNotFoundException- Class not found
12. IllegalAccessException- Access to class is denies.
13. InstantialException- attempt to create an object of an abstract class o interface.
14. NoSuchMethodException- A requested method does not exist.
9.4 Summary
In this chapter the exceptions, handling errors, catching exceptions, throwing exceptions were studied in detail. The exceptions of Java help in deciding and tracing errors in programs.
Media Attributions
- 9.1 Throwable Heirarchy