Introduction to Java Programming Language
Unit-11 [Exception Handling]
The exception handling in java is used to handle the runtime errors so that normal flow of the
application can be maintained. A Java Exception is an object that describes the exception that occurs
in a program. When an exceptional events occurs in java, an exception is said to be thrown. The
code that's responsible for doing something about the exception is called an exception handler.
Exception Class Hierarchy
All exception types are subclasses of class Throwable, which is at the top of exception class
hierarchy.
Below is a brief description of all classes mentioned here:
• Exception class is for exceptional conditions that program should catch. This class is
extended to create user specific exception classes.
• RuntimeException is a subclass of Exception. Exceptions under this class are automatically
defined for programs.
• Exceptions of type Error are used by the Java run-time system to indicate errors having to
do with the run-time environment, itself. Error is irrecoverable e.g. OutOfMemoryError,
VirtualMachineError, Stack OverflowError.
Types of Exception:
1. Checked exceptions: Checked exceptions are checked at compile-time. Note that, the classes
that extend Throwable class except RuntimeException and Error are known as checked exceptions.
e.g.IOException, SQLException etc.
2. Unchecked Exception: The classes that extend RuntimeException are known as unchecked
exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException
etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
3. Errors: These are typically ignored in code because you can rarely do anything about an error.
Example :if stack overflow occurs, an error will arise. This type of error cannot be handled in the
code.
Provided By Shipra Swati
Introduction to Java Programming Language
Examples:
1) ArithmeticException occurs: If we divide any number by zero, there occurs an
ArithmeticException.
Int a=50/0; //ArithmeticException
2) Scenario where NullPointerException occurs: If we have null value in any variable,
performing any operation by the variable occurs an NullPointerException.
String s=null;
System.out.println(s.length()); //NullPointerException
3) Scenario where NumberFormatException occurs: The wrong formatting of any value, may
occur NumberFormatException. Suppose I have a string variable that have characters, converting
this variable into digit will occur NumberFormatException.
String s="abc";
int i=Integer.parseInt(s); //NumberFormatException
4) Scenario where ArrayIndexOutOfBoundsException occurs: If you are inserting any value in
the wrong index, it would result ArrayIndexOutOfBoundsException as shown below:
Int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
There are 5 keywords used in java exception handling:
1. try
2. catch
3. finally
4. throw
5. throws
Java Program of Exception Example:
class Excp{
 public static void main(String args[]) {
  int a,b,c;
  try {
   a=0;
   b=10;
   c=b/a;
   System.out.println("This line will not be executed");
  }
  catch(ArithmeticException e)  {
   System.out.println("Divided by zero"); 
  }
  System.out.println("After exception is handled");
 }
}
Output
Divided by zero
After exception is handled
Provided By Shipra Swati
Introduction to Java Programming Language
Try is used to guard a block of code in which exception may occur. This block of code is called
guarded region. A catch statement involves declaring the type of exception you are trying to catch.
If an exception occurs in guarded code, the catch block that follows the try is checked, if the type of
exception that occured is listed in the catch block then the exception is handed over to the catch
block which then handles it.
An exception will be thrown by this program as we are trying to divide a number by zero inside try
block. The program control is transferred outside try block. Thus the line "This line will not be
executed" is never parsed by the compiler. The exception thrown is handled in catch block. Once
the exception is handled, the program control is continue with the next line in the program i.e after
catch block. Thus the line "After exception is handled" is printed.
Exceptions throws and throw clause
throw clause
throw keyword is used to throw an exception explicitly. Only object of Throwable class or its sub
classes can be thrown. Program execution stops on encountering throw statement, and the closest
catch statement is checked for matching type of exception.
Syntax :
throw ThrowableInstance
Provided By Shipra Swati
Introduction to Java Programming Language
Example:
class Test{
 static void avg()  {
  try
  {
   throw new ArithmeticException("demo");
  }
  catch(ArithmeticException e)  {
   System.out.println("Exception caught");
  } 
 }
 public static void main(String args[]) {
  avg(); 
 }
}
new   ArithmeticException("demo")  constructs an instance of ArithmeticException with
name “demo”. The avg() method throw an instance of ArithmeticException, which is successfully
handled using the catch statement and thus, the program outputs:
"Exception caught"
throws clause
Any method that is capable of causing exceptions must list all the exceptions possible during its
execution, so that anyone calling that method gets a prior knowledge about which exceptions are to
be handled. A method can do so by using the throws keyword.
General syntax of throws:
type method_name(parameter_list) throws exception_list
{
 //definition of method
}
Example:
class Test{
 static void check() throws ArithmeticException {
  System.out.println("Inside check function");
  throw new ArithmeticException("demo");
 }
 public static void main(String args[]) {
  try  {
   check();
  }
  catch(ArithmeticException e)  {
   System.out.println("caught" + e);
  }
 }
}
Provided By Shipra Swati
Introduction to Java Programming Language
Output
Inside check function
caughtjava.lang.ArithmeticException: demo
Difference between throw and throws
throw throws
throw keyword is used to throw an exception
explicitly.
throws keyword is used to declare an exception
possible during its execution.
throw keyword is followed by an instance of
Throwable class or one of its sub-classes.
throws keyword is followed by one or more
Exception class names separated by commas.
throw keyword is declared inside a method
body.
throws keyword is used with method signature
(method declaration).
We cannot throw multiple exceptions using
throw keyword.
We can declare multiple exceptions (separated by
commas) using throws keyword.
finally clause
A finally keyword is used to create a block of code that follows a try block. A finally block of code
is always executed whether an exception has occurred or not. Using a finally block, it lets you run
any cleanup type statements that you want to execute, no matter what happens in the protected code.
A finally block appears at the end of catch block.
In the following example, you can see in above example even if exception is thrown by the
program, which is not handled by catch block, still finally block will get executed.
Example
Class ExceptionTest{
 public static void main(String[] args) {
  int a[]= new int[2];
  System.out.println("out of try");
  try   {
   System.out.println("Access invalid element"+ a[3]);
   /* the above statement will throw ArrayIndexOutOfBoundException */
  }
  finally   {
   System.out.println("finally is always executed.");
  }
 }
}
Output
Out of try
finally is always executed.
Exception in thread main java. Lang. exception array Index out of bound exception.
Provided By Shipra Swati
Introduction to Java Programming Language
Related University Question
1. Discuss java error handling mechanism. What is the difference between runtime (unchecked)
exceptions and checked exceptions? what is the implication of catching all the exceptions with the
type 'exception'?
[Year 2015]
2. What is exception handling? What are the statements used for it? Show an example. [Year 2016]
Provided By Shipra Swati

Java unit 11

  • 1.
    Introduction to JavaProgramming Language Unit-11 [Exception Handling] The exception handling in java is used to handle the runtime errors so that normal flow of the application can be maintained. A Java Exception is an object that describes the exception that occurs in a program. When an exceptional events occurs in java, an exception is said to be thrown. The code that's responsible for doing something about the exception is called an exception handler. Exception Class Hierarchy All exception types are subclasses of class Throwable, which is at the top of exception class hierarchy. Below is a brief description of all classes mentioned here: • Exception class is for exceptional conditions that program should catch. This class is extended to create user specific exception classes. • RuntimeException is a subclass of Exception. Exceptions under this class are automatically defined for programs. • Exceptions of type Error are used by the Java run-time system to indicate errors having to do with the run-time environment, itself. Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, Stack OverflowError. Types of Exception: 1. Checked exceptions: Checked exceptions are checked at compile-time. Note that, the classes that extend Throwable class except RuntimeException and Error are known as checked exceptions. e.g.IOException, SQLException etc. 2. Unchecked Exception: The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime. 3. Errors: These are typically ignored in code because you can rarely do anything about an error. Example :if stack overflow occurs, an error will arise. This type of error cannot be handled in the code. Provided By Shipra Swati
  • 2.
    Introduction to JavaProgramming Language Examples: 1) ArithmeticException occurs: If we divide any number by zero, there occurs an ArithmeticException. Int a=50/0; //ArithmeticException 2) Scenario where NullPointerException occurs: If we have null value in any variable, performing any operation by the variable occurs an NullPointerException. String s=null; System.out.println(s.length()); //NullPointerException 3) Scenario where NumberFormatException occurs: The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string variable that have characters, converting this variable into digit will occur NumberFormatException. String s="abc"; int i=Integer.parseInt(s); //NumberFormatException 4) Scenario where ArrayIndexOutOfBoundsException occurs: If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException as shown below: Int a[]=new int[5]; a[10]=50; //ArrayIndexOutOfBoundsException There are 5 keywords used in java exception handling: 1. try 2. catch 3. finally 4. throw 5. throws Java Program of Exception Example: class Excp{  public static void main(String args[]) {   int a,b,c;   try {    a=0;    b=10;    c=b/a;    System.out.println("This line will not be executed");   }   catch(ArithmeticException e)  {    System.out.println("Divided by zero");    }   System.out.println("After exception is handled");  } } Output Divided by zero After exception is handled Provided By Shipra Swati
  • 3.
    Introduction to JavaProgramming Language Try is used to guard a block of code in which exception may occur. This block of code is called guarded region. A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in guarded code, the catch block that follows the try is checked, if the type of exception that occured is listed in the catch block then the exception is handed over to the catch block which then handles it. An exception will be thrown by this program as we are trying to divide a number by zero inside try block. The program control is transferred outside try block. Thus the line "This line will not be executed" is never parsed by the compiler. The exception thrown is handled in catch block. Once the exception is handled, the program control is continue with the next line in the program i.e after catch block. Thus the line "After exception is handled" is printed. Exceptions throws and throw clause throw clause throw keyword is used to throw an exception explicitly. Only object of Throwable class or its sub classes can be thrown. Program execution stops on encountering throw statement, and the closest catch statement is checked for matching type of exception. Syntax : throw ThrowableInstance Provided By Shipra Swati
  • 4.
    Introduction to JavaProgramming Language Example: class Test{  static void avg()  {   try   {    throw new ArithmeticException("demo");   }   catch(ArithmeticException e)  {    System.out.println("Exception caught");   }   }  public static void main(String args[]) {   avg();   } } new   ArithmeticException("demo")  constructs an instance of ArithmeticException with name “demo”. The avg() method throw an instance of ArithmeticException, which is successfully handled using the catch statement and thus, the program outputs: "Exception caught" throws clause Any method that is capable of causing exceptions must list all the exceptions possible during its execution, so that anyone calling that method gets a prior knowledge about which exceptions are to be handled. A method can do so by using the throws keyword. General syntax of throws: type method_name(parameter_list) throws exception_list {  //definition of method } Example: class Test{  static void check() throws ArithmeticException {   System.out.println("Inside check function");   throw new ArithmeticException("demo");  }  public static void main(String args[]) {   try  {    check();   }   catch(ArithmeticException e)  {    System.out.println("caught" + e);   }  } } Provided By Shipra Swati
  • 5.
    Introduction to JavaProgramming Language Output Inside check function caughtjava.lang.ArithmeticException: demo Difference between throw and throws throw throws throw keyword is used to throw an exception explicitly. throws keyword is used to declare an exception possible during its execution. throw keyword is followed by an instance of Throwable class or one of its sub-classes. throws keyword is followed by one or more Exception class names separated by commas. throw keyword is declared inside a method body. throws keyword is used with method signature (method declaration). We cannot throw multiple exceptions using throw keyword. We can declare multiple exceptions (separated by commas) using throws keyword. finally clause A finally keyword is used to create a block of code that follows a try block. A finally block of code is always executed whether an exception has occurred or not. Using a finally block, it lets you run any cleanup type statements that you want to execute, no matter what happens in the protected code. A finally block appears at the end of catch block. In the following example, you can see in above example even if exception is thrown by the program, which is not handled by catch block, still finally block will get executed. Example Class ExceptionTest{  public static void main(String[] args) {   int a[]= new int[2];   System.out.println("out of try");   try   {    System.out.println("Access invalid element"+ a[3]);    /* the above statement will throw ArrayIndexOutOfBoundException */   }   finally   {    System.out.println("finally is always executed.");   }  } } Output Out of try finally is always executed. Exception in thread main java. Lang. exception array Index out of bound exception. Provided By Shipra Swati
  • 6.
    Introduction to JavaProgramming Language Related University Question 1. Discuss java error handling mechanism. What is the difference between runtime (unchecked) exceptions and checked exceptions? what is the implication of catching all the exceptions with the type 'exception'? [Year 2015] 2. What is exception handling? What are the statements used for it? Show an example. [Year 2016] Provided By Shipra Swati