Ch-10
Exception handling in Java
errors in a program
There are two types of errors that can prevail in a program.
All kinds of error conditions are called exceptions.
A compile error is normally a syntax error. It occurs when there is something missing in a statement. A compile error does not allow to successfully compile a program. If there is any syntax error in the program we will get a compilation error and will not be able to create the .class file.
Some common syntax errors are (1) missing semicolon, (2) use of undeclared variable, (3) Wrong spellings of identifier or keyword and (4) mismatch of bracket.
Run time error
If there are no syntax errors in the source code then the program will compile successfully and we will get a .class file.
However this does not guarantee that the program will execute as per our expectations.
A Run time error can occur in spite of successful compilation.
A Run time error occurs at run time ie. While executing a program.
Example of a run time error
The following program get compiled successfully, but it shows error at run time.
It is because there are total 4 elements in ctylist array and we have tried using 5th
Element which is not available. This program shows following run time error.
The output contains a phrase �“ArrayIndexOutOfBoundsException”.
For each type of exception, there are corresponding exception classes in Java.
The java.lang and java.io package contains a hierarchy of classes dealing with various exceptions.
Few widely observed exceptions
Exception Class | Condition resulting in Exception | Example |
ArrayIndexOutOfBoundsException | Attempt to access array element with an index value that is outside the range of array | Int a[] = new int[4] a[13] = 99 |
ArithmeticException | An attempt to divide any number by 0 | Int a = 50/0; |
FileNotFoundException | At attempt to access a non-existing file. | |
NullPointerException | An attempt to use null in a case where an object is required | String s = null; System.out.print(s.length()); |
NumberFormatException | An attempt to convert string to a number type | String s=“xyz”; Int I = Integer.parseInt(s); |
PrinterIOException | An I/O error has occurred while printing | |
Exception Handling
An exception is an error condition.
Exception handling is an object oriented technique for managing errors.
While performing exception handling, we try to ensure that the program does not terminate abruptly nor does it generate unexpected output.
Java uses 3 keywords : try, catch and finally to write an exception handler.
In short when a run time error occurs, the program should not stop abruptly. Instead it should show our own error message.
When a run time error occurs JVM creates an exception object(eobj) and throws it automatically. If any code is written for handling this exception, then the control is transferred towards particular exception handler.
The try block:
A try block contains the code that may give rise to one or more exceptions.
The catch block:
A catch block contains the code that is intended to handle exceptions of a particular type created in the associated try block
The finally block:
A finally block is always executed before the program ends, regardless of whether any exceptions are generated in the try block or not.
The try block:
The try statement contains a block of statements that we want to monitor for exception.
For eg.
Try
{
System.out.println(citylist[5]);
}
After try block there must be catch block written either to solve exception or to display our own proper message.
The catch block:
The catch block contains the code that is to be executed to handle an exception.
The catch is an exception handler.
There can be one or more catch blocks for a single try block.
Try Block
Statements that may
Cause exceptions of
Different types
Catch Block
Statements that
Handles exceptions
Creates Exception
Exception Handler
Program illustrating try … catch blocks
This program instead of showing any run time error displays, the message written between �Catch block.
When a run time error occurs, the try block instead of showing error throws the control �towards corresponding catch block.
The corresponding catch block handles the exception and does not allow program �to terminate unexpectedly. It shows our own message as below.
The “finally” block:
The “finally” block is generally used to clean up at the end of executing a try block.
We use a finally block when we want to be sure that some particular code is to be run, no matter what exceptions are thrown with the associated try block.
A finally block is always executed, regardless of whether or not exceptions are thrown during the execution of the associated try block.
A finally block is widely used if a file needs to be closed or a critical resource is to be released at the completion of the program.
Program illustrating “finally” block
Output
How many types of errors are there?
2
Name the various types of errors.
Compile time error & Run time error
All kind of error conditions are known as _____________.
Exceptions
Syntax errors are known _____________ errors.
Compile time erros
Which type of error does not allow to create .class file?
Compile time error
___________ error can occur in spite of successful compilation.
Run time error
The __________ and __________package contains a hierarchy of classes dealing with various exceptions.
java.lang and java.io
Which run time error occurs when an array element is referred that is not available?
ArrayIndexOutOfBoundsException
Which run time exception occurs when any number is divided by zero?
ArithmeticException
Which exception is occurred when we try to access file which is not available?
FileNotFoundException
Which run time error occurs when printer is not connected?
PrinterIOException
Exception handling techniques are done by how many keywords?
3
___________ is created by JVM when a run time error occurs.
exception object(eobj)
___________ contains the code that may give rise to one or more exceptions.
Try block
________ contains the code that is intended to handle exceptions of a particular type created in the associated try block
Catch block
____________ is always executed before the program ends, regardless of whether any exceptions are generated in the try block or not.
finally block
___________ contains the code that may give rise to one or more exceptions.
Try block
________ contains the code that is intended to handle exceptions of a particular type created in the associated try block
Catch block
Multiple catch blocks
In a single program multiple exceptions can occur.
For eg. If we want to upload a particular file to a remote computer, it may lead to two distinct exceptions.
- Exception may occur if file is not present. or
- exception may occur if system is not connected to network.
If the try block throws several different kinds of exceptions, we can write multiple catch blocks, each handling a specific exception.
Try Block
Statements that may
Cause exceptions of
Different types
Catch Block-1
Statements that
Handles exceptions
Creates
Exception
Exception
Handler
Catch Block-2
Statements that
Handles exceptions
Exception
Handler
Program illustrating multiple catch blocks
The last catch block can handle any type of exception.
It is a kind of default catch block and must be the last block when there are multiple �catch blocks
While writing program, the order of specific catch blocks does not matter but the default �Block has to be placed at the end of all catch blocks.
The throw statement
Normally JVM creates an exception object and throws it automatically.
The corresponding catch block takes the control.
The throw keyword is used to throw an exception.
The object that we throw must be of type java.lang.
When a throw statement is encountered, a search for matching catch block begins.
Program illustrating throw statement
Output
The throws clause
Throws clause is used if an exception occurs in a method or a constructor.
There are two alternate approaches to handle exceptions created byu a method:
(1) Write a try-catch block within the method
(2) Invoking a method within a try block
Program illustrating throws clause
Output