Archive for Java

Exception Handling in Java

Wednesday, May 11th, 2011

By: Pankaj Yadav

Exceptions are the error those may lead to incorrect output or may terminate the execution of program and may even cause system crash.

Types of Exceptions

  • 1. Compile time Exception
  • 2. Run Time Exception

Compile time Exception

These exceptions may rise during compilation of program. And these errors may be raised by the compiler. There may be the following reasons for exception:

We can declare fields as follows:

  • 1. Due to missing of semi colon.
  • 2. Due to missing class and method bracket
  • 3. Misspelling of the identifiers and keywords
  • 4. Missing double quotation in strings
  • 5. Used of undeclared variables
  • 6. Incomplete types in assignment/initialization
  • 7. Use of Bad reference object

Run-time Exception

These exceptions may rise during run of program. Most of the common exceptions may rise due to:

  • 1. Dividing by zero
  • 2. Accessing element out of the index of the array
  • 3. Trying to insert values of the variable not of the type

Steps for Exception Handling

  • 1. Find the problem (Hit exception)
  • 2. Inform about the exception(Throw exception)
  • 3. Receive the exception(Catch exception)
  • 4. Correct the exception(Handling exception)

Syntax of Exception Handling

try
{
statements			//generates an exception
}
catch (Exception e)
{
statement			//process the exception
}

Multiple catch Statements

It is possible to have more than one catch statement in the catch block

Syntax for method:

 

Using finally

Java supports finally statement that can be used to handle exception that is not caught by any previous catch statement. Finally block is used to handle any error generated in the try block.

Syntax

	try
		{
			//		statement
		}
		catch(ExceptionSubClass1 ex1)
		{
			//		statements
		}
		catch(ExceptionSubClass2 ex2)
		{
			//		statements
		}
		finally
		{
			//		statements
		}

User Defined Exception

There are many times when we have to throw exceptions .This we can do with the help of throw as follows:


throw new ArithmaticException();
throw new NumberFormatException();

Note: Mainly all user defined classes are subclass of Throwable.

Example

import java.lang. Exception;

class MyException extends Exception
{

	MyException(String message)
	{
		super(message);
	}

}

class TestmMyException
{

	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 small");
			}
		}
		catch(MyException e)
		{
			System.out.println("Exception caught");
		}
		finally
		{
			System.out.println("Finally bloc Always executes");
		}
	}

}

output


Exception caught
Finally bloc Always executes
Press any key to continue…