analytics

Saturday, March 26, 2011

Exception Handling Basics

What is an Exception?


Exception is an abnormal condition that occurs during program execution and is (Usually) an indicative of some kind of failure or error condition.

Exception can occur when:

  • The file you are trying to open does not exist.
  • The network connection is disrupted.
  • Operands being manipulated are out of prescribed ranges.

Example:

int[] arr=new int[4];
System.out.println(arr[4]);

The preceding line will throw an ArrayIndexOutOfBoundsException.

Java defines the Throwable class to handle the exception and error conditions.

The two subclasses of Throwable class are:

  • Exception class: Represents mild error conditions that can be handled so that the program does not terminate.

  • Error class: Defines serious error conditions from which you should not attempt to recover. In most cases, the program is terminated when it encounters this type of an error.
Handling an Exception

Normally, when a program encounters an exception condition, it throws the exception and terminates with an error message.

Java provides a mechanism for figuring out which exception was thrown and how to recover from it.


Exception handling allows a program to catch the exception, handle the exception, and then continue the program execution.

Try block: To handle a particular exception, place the code that might throw an exception inside the try block.


Catch block:

• Is the exception handler

• Should be declared immediately after the try block, one for each possible exception that can be thrown

• A single try block can have multiple catch blocks to handle different exception type

• Catch accepts the Throwable object as the argument

Example:

try{
int[] arr=new arr[4];
System.out.println(arr[4]);
}catch(ArrayIndexOutOfBoundsException e){
//Handler code
}


Finally block:

• Finally statement defines a block of code that always executes, regardless of whether the exception was caught.

• The try block should be defined with catch and/or with the finally block.

Call stack mechanism:

• If the exception is not handled in the calling method, it is thrown to the caller of that method.

• This process continues until the exception is handled.

• If the exception is not handled till the main method, it terminates the program abnormally.


Exception Class Hierarchy










throw Keyword

The throw keyword is used to throw the exceptions explicitly:

  • For rethrowing an exception
  • In custom exceptions
Syntax:

throw ThrowableInstance;

• Types of exceptions:

  • Checked exceptions: Subclasses of the Exception class that must be handled or declared, otherwise fatal compiler error will be issued.
  • Unchecked exceptions: Subclasses of RuntimeException. No need to

provide the handler code.

Note: RuntimeException is a subclass of Exception.


throws Clause

• If a method does not provide the handler for the exception thrown by it, then the exception is passed to the caller.

• The throws keyword lists the type of exceptions that a method might throw.

• The throws clause used as a indicator to the caller of the method to know about the exceptions thrown by the particular method.

• The throws clause specified in the signature of the method.

• A method may declare that it would throw more than one exception.

• The throws clause is required for checked exceptions, if not handled in try / catch blocks.


Custom Exceptions


• User-defined exceptions or custom exceptions are created by extending the Exception class.

• This exception classes can define variables, constructors, and methods as regular classes:

public class CustomException extends Exception{
private String exceptData;
public CustomException(String message,String exceptData){
super(message);//invokes base class constructor
this.exceptData=exceptData;
}
}

• The following is the syntax for throwing the custom exceptions,

throw new CustomException(“CustomException”,”some failure”);


Custom Exception Example

/*
* CreateException.java
* This create exception is thrown when the customer object
* cannot be created
*/

public class CreateException extends Exception{
public CreateException(String message){
super(message);
}
}

/*
* Customer.java
*/

Public class Customer{
private String name;
private int age;
public Customer(String n, int a)throws CreateException{
if(a<18 a>55){
throw new CreateException(“Age limit of the customer is 18 to 55”);
}
name=n;
age=a;
}

public void print(){
System.out.println(“Name “+name+” “+”age ” +age);
}
}

/*
* CustomerDemo.java
*/

public class CustomerDemo{
public static void main(String args[]){
Customer cust[]=new Customer[2];
for(int i=0;i<2;i++){
try{
c[0]=new Customer(“Ram”,60);
c[0].print();
}catch(CreateException e){
System.out.println(“The customer object is not created”);
System.out.println(e.getMessage());
}
}
}
}

No comments:

Post a Comment