Java Exception Handling

What is an Exception?

Java Exception Examples

  1. Divide by zero errors
  2. Accessing the elements of an array beyond its range
  3. Invalid input
  4. Hard disk crash
  5. Opening a non-existent file
  6. Heap memory exhausted
/* Java Exception Example 1 */
/* Save with file name ExceptionExample1.java */

public class ExceptionExample1
{
	public static void main(String args[])
	{
		System.out.println(3/0);
		System.out.println("No Exception Occurred");
	}
}
                        

The default exception handler provided by java runtime will prints out the exception description, stack trace (Hierarchy of methods where the exception occurred) and Causes the program to terminate. The Exception message looks like the following message.

Exception in thread "main" java.lang.ArithmeticException: / by zero
     at ExceptionExample1.main(ExceptionExample1.java:8)

What Happens When an Exception Occurs?

  • When an exception occurs within a method, the method creates an exception object and hands it off to the runtime system.
  • The runtime system searches the call stack for a method that contains an exception handler
  • When an appropriate handler is found, the runtime system passes the exception to the handler
  • If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, the runtime system (and, consequently, the program) terminates and uses the default exception handler

Benefits of Java Exception Handling

  • Separating Error-Handling code from regular business logic code
  • Propagating errors up the call stack
  • Grouping and differentiating error types

Separating Error Handling Code from Regular Code

Exceptions enable you to write the main flow of your code and to deal with the exceptional cases elsewhere. Note that exceptions don't spare you the effort of doing the work of detecting, reporting, and handling errors, but they do help you organize the work more effectively.

Catching Exceptions in Java with try-catch

Syntax:
try
{
	< code to be monitored for exceptions >
}
catch(< ExceptionType1 > < ObjName >)
{
	< handler if ExceptionType1 occurs >
}
...
}
catch (< ExceptionTypeN > < ObjName >)
{
	< handler if ExceptionTypeN occurs >
}
/* Java Exception Example 2 */
/* Save with file name ExceptionExample2.java */

public class ExceptionExample2
{
	public static void main(String args[])
	{
		try
		{
			System.out.println(3/0);
			System.out.println("No Exception Occurred");
		}
		catch(ArithmeticException ae)
		{
			System.out.println(ae);
		}
	}
}
                        

Catching Exceptions in Java with multiple catch

Multiple catches should be ordered from subclass to super class.

/* Java Exception Example 3 */
/* Save with file name ExceptionExample3.java */

public class ExceptionExample3
{
	public static void main(String args[])
	{
		try
		{
			int nos[] = new int[7];
			//throw ArrayIndexOutOfBoundsException exception
			nos[10] = 777;
			System.out.println(3/0);
			System.out.println("No Exception Occurred");
		}
		catch(ArithmeticException ae)
		{
			System.out.println("Arithmetic Exception : "+ae);
		}
		catch(ArrayIndexOutOfBoundsException arre)
		{
			System.out.println("ArrayIndexOutOfBoundsException : "+arre);
		}
	}
}
                        
Catching Exceptions in Java with nested try-catch
/* Java Exception Example 4 */
/* Save with file name ExceptionExample4.java */

public class ExceptionExample4
{
	public static void main(String args[])
	{
		try
		{
			try
			{
				int nos[] = new int[7];
				//throw ArrayIndexOutOfBoundsException exception
				nos[10] = 777;
			}
			catch(ArrayIndexOutOfBoundsException arre)
			{
				System.out.println("Arithmetic Exception : "+arre);
			}
			System.out.println("No Exception Occurred in outer try-block");
		}
		catch(Exception ex)
		{
			System.out.println("Some other Exception : "+ex);
		}
	}
}
                        

Catching Exceptions in java with finally

The finally block code is always executed.

/* Java Exception Example 5 */
/* Save with file name ExceptionExample5.java */

public class ExceptionExample5
{
	public static void main(String args[])
	{
		try
		{
			System.out.println("try Block Executed");
		}
		catch(ArithmeticException ae)
		{
			System.out.println("catch Block Executed");
		}
		finally
		{
			System.out.println("finally block always Executed");
		}
	}
}
                        

Throwing Exceptions with throw keyword

Java allows you to throw exceptions (generate exceptions). An exception you throw is an object.

/* Java Exception Example 6 */
/* Save with file name ExceptionExample6.java */

public class ExceptionExample6
{
	public static void main(String args[])
	{
		try
		{
			int value = 0;
			if(value == 0)
			{
				throw new Exception("Value Should not Zero!");
			}
			System.out.println("No Exception Occurred");
		}
		catch(Exception ex)
		{
			System.out.println(ex);
		}
	}
}
                        

Rules in Java Exception Handling

  • A method is required to either catch or list all exceptions it might throw
    —   Except for Error or RuntimeException, or their subclasses
  • If a method may cause an exception to occur but does not catch it, then it must say so using the throws keyword
    —   Applies to checked exceptions only

Checked exception

  • Java compiler checks if the program either catches or lists the occurring checked exception
  • If not, compiler error will occur

Unchecked exceptions

  1. Not subject to compile-time checking for exception handling
  2. Built-in unchecked exception classes Error, RuntimeException and Their subclasses
  3. Handling all these exceptions may make the program cluttered and may become a nuisance

Creating Your Own Exception Class

Steps to follow

  1. Create a class that extends the RuntimeException or the Exception class
  2. Customize the class i.e. Members and constructors may be added to the class

How To Use Your Own Exceptions

The following example shows how to use your own exceptions in java.

/* Save with file name MyOwnException.java */
public class MyOwnException extends Exception
{
	String msg = null;
	public MyOwnException(String msg)
	{
		super(msg);
		this.msg = msg;
	}

	public String printWhatHappened()
	{
		if(msg == null)
			return "";
		else
			return msg;
	}
}
                        
/* Java Exception Example 7 */
/* Save with file name ExceptionExample7.java */
public class ExceptionExample7
{
	public static void main(String args[])
	{
		try
		{
			int value = 0;
			if(value == 0)
			{
				throw new MyOwnException("Value Should not Zero!");
			}
			System.out.println("No Exception Occurred");
		}
		catch(MyOwnException ex)
		{
			System.out.println(ex.printWhatHappened());
		}
	}
}