Menus

Mar 17, 2017

Exception Handling In Java

Course Contents:
1.   Error and exception
2.   Types of exception
3.   Mechanism for exception handling

Error
It is common to make mistakes while developing as well as typing a program. A mistake might lead to an error causing the program to produce unexpected results. An error may produce an incorrect output or may terminate the execution of the program abruptly of even may cause the system to crash. It is therefore important to detect and manage properly all the possible error conditions in the program so that the program will not terminate or crash during execution.

Types of errors
Errors are broadly classified into two categories:
- Compile time errors
- Run-time errors


Compile time errors
Those errors that encounter at compilation time are known as compile time errors. All syntax errors will be detected and displayed by the java compiler and therefore these errors are known as compile time errors. Whenever the compiler displays an error, it will not create the .class file.

It is therefore necessary that all the errors should be fixed before successfully compile and run the program. Most of the compile time errors are due to typing mistakes. The most common compile time errors are:
- Missing semicolon
- Missing (or mismatch of) brackets in classes and methods
- Misspelling of identifiers and keywords
- Missing double quotes in string
- Use of undeclared variables
- Incompatible types in assignment/initialization
- Bad reference to objects
- And so on.

Run time errors
All the errors that encounter at run time are known as run time errors. During runtime errors a program may compile successfully creating the .class file but may not run properly. Such programs may produce wrong results due to wrong logic or may terminate due to errors. Most common runtime errors are:
- Dividing an integer by zero.
- Accessing an element that is out of the bounds of an array.
- Trying to store a value into an array of an incompatible class or type.
- Trying to cast an instance of a class to one of its subclasses
- Passing a parameter that is not in a valid range or value for a method
- Trying to illegally change the state of a thread
- Attempting to use a negative size for an array
- Converting invalid string to a number
- Accessing a character that is out of bounds of a string
- And so on.

Exceptions
An exception is a condition that is caused by a runtime error in the program. When the Java interpreter encounters an error such as dividing an integer by zero, it creates an exception object and throws (i.e., inform us that an error has occurred).
If the exception object is not caught and handled properly, the interpreter will display an error message and will terminate the program. To continue the program execution, we should try to
catch the exception object thrown by the error condition and then display an appropriate message for taking corrective actions. This task is known as exception handling. The purpose of exception
handling is to provide a means to detect and report an exceptional circumstance so that appropriate action can be taken.

Java exception handling is managed by five keywords: try, catch, throw, throws and finally.
Program statements that may generate exception are contained within try block. If an exception occurs within the try block, it is thrown. Those statements that are used to catch those exceptions
are kept in catch block and handled in some relational manner. System generated exceptions are automatically thrown by the java runtime system. To manually throw an exception, use the keyword throw. Any exception that is thrown out of a method must be specified as such by a throws clause. Any code that absolutely must be executed before a method returns is put in a finally block.

The general syntax of exception handling block is:
try
{
// block of code to monitor for errors
}
catch(Exception_type1 exob)

{
//exception handler for exception type1
}
catch(Exception_type2 exob)
{
//exception handler for exception type2
}
//…………………
finally
{
//block of code to be executed before try block ends
}
Here, exception type is the type of exception that has occurred.



 Fig: exception hierarchy

Exception type
 All exception types are subclasses of the built-in class Throwable. Thus Throwable is at the top of the exception class hierarchy. Immediately below Throwable are two subclasses that partition exceptions into two distinct branches: error and exception. There is an important subclass of exception, called RuntimeException. The other branch called error, which define exceptions that are not expected to be caught under normal circumstances by the program.

Using try and catch
The code that may generate exception is enclosed within try block. Immediately following try block, include a catch clause that specifies the exception type that you wish to catch.

Program which includes try and catch block that processes the ArithmeticException generated by the division-by-zero error.
class Exception{
public static void main(String args[]){
int a,b;
try{
b = 0;
a = 12/b;
System.out.println(" Inside try block");
// this will not be printed
}
catch(ArithmeticException e){
//catch division by zero error
System.out.println("Division by zero.");
}
System.out.println("Outside try and catch block");
}
}
Output
Division by zero.
Outside try and catch block
Multiple catch clauses

In some cases, more than one exception could be raised by a single piece of code. To handle this type of situation, we can specify two or more catch clauses, each catching a different type of exception. When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed. After one catch statement executes, the others are bypassed and execution continues after the try/catch block.
Syntax
try
{
Statements;
}
catch (exception_type1 e)
{
Statements;
} 
catch (exception_type2 e)
{
Statements;
}
………….
………..
catch (exception_typeN e)
{
Statement;
}

Write a program that demonstrat e the concept of multiple catch blocks
class MultipleCatch{
public static void main(String args[]){
int a[] = {5,10};
int b = 5;
try{
int x = a[2]/(b-a[ 1] );
}
catch(ArithmeticException e){
System.out.println("Division by zero");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Array index error");
}
catch(ArrayStoreException e){
System.out.println("Wrong data type");
}
int y = a[1]/a[0] ; 
System.out.println("Y= " +y);
}
}
Output
Array index error
Y=2

finally statement
Java supports another statement known as finally statement that can be used to handle an exception that is not caught by any of the previous catch statements. finally block can be used to handle any exception generated within a try block. It may be added immediately after the try
block or after the last catch block.
try
{
……….
………
}
finally
{
………..
………..
}

Or
try
{
………..
………..
}
catch(………)
{
…………
…………
}
catch(……..)
{
………..
………..
}
………….
…………

finally
{
………..
………..
}

WAP that demonstrate the concept of finally
class MultipleCatch{
public static void main(String args[]){
int a[] = {5,10};
int b = 5;
try{
int x = a[2]/(b-a[ 1] );
}
catch(ArithmeticException e){
System.out.println("Division by zero");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Array index error");
}
catch(ArrayStoreException e){
System.out.println("Wrong data type");
}
finally{
int y = a[1]/a[0] ;
System.out.println("Y= " +y);
}
}
}

throw
When we would like to throw our own exceptions, we can do this by using the keyword throw.
The general syntax of throw is as:
throw new throwableinstance;
Here, throwableinstance must be an object of type Throwable or a subclass of throwable. The flow of execution stops immediately after the throw statement, any subsequent statements are not executed.
Program that demonstrate the concept of throw
import java.lang.Exception;
class MyException extends Exception{
MyException(String message){
super(message);
}
}

class TestMyException{
public static void main(String args[]){
int x = 5, y = 1000;
try{
float z = (float) x / (float) y;
if(z < 0.01){
throw new MyException("Number is too small");
}
}
catch( MyException e){
System.out.println("Caught my Exception");
System.out.println(e.getMessage());
}
finally{
System.out.println("I am always here");
}
}
}
Output
Caught my Exception
Number is too small
I am always here

No comments:

Post a Comment

Contact Form

Name

Email *

Message *