Exceptions in Java: Dictionary Meaning: Exception is an abnormal condition.
Exception Handling in Java is one of the effective means to handle the runtime errors so that the regular
flow of the application can be preserved. Java Exception Handling is a mechanism to handle runtime
errors such as ClassNotFoundException, IOException, SQLException etc.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.
Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at
run time, that disrupts the normal flow of the program’s instructions. Exceptions can be caught and
handled by the program. When an exception occurs within a method, it creates an object. This object is
called the exception object. It contains information about the exception, such as the name and
description of the exception and the state of the program when the exception occurred.
Major reasons why an exception Occurs
• Invalid user input
• Device failure
• Loss of network connection
• Physical limitations (out of disk memory)
• Code errors
• Opening an unavailable file
• Error: Errors are problems that mainly occur due to the lack of system resources. It cannot be caught or handled. It
indicates a serious problem. It occurs at run time. These are always unchecked. An example of errors
is OutOfMemoryError, LinkageError, etc. are the subclasses of the Error class.
• Exception: These are the errors that occur at compile time and run time. It occurs in the code written by the
developers. It can be recovered by using the try-catch block and throws keyword. There are two types of exceptions
i.e. checked and unchecked.
Exception Hierarchy:
Types of Exceptions
Java defines several types of exceptions that relate to its various class libraries. Java also allows users
to define their own exceptions.
Hierarchy Exception
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error are known
as checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are
checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For example,
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked
exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError,
AssertionError etc.
Checked Exception Unchecked Exception
Checked exceptions occur at compile time. Unchecked exceptions occur at runtime.
The compiler checks a checked exception. The compiler does not check these types of exceptions.
These types of exceptions can be handled at the time of
compilation.
These types of exceptions cannot be a catch or handle at the
time of compilation, because they get generated by the
mistakes in the program.
They are the sub-class of the exception class. They are runtime exceptions and hence are not a part of the
Exception class.
Here, the JVM needs the exception to catch and handle. Here, the JVM does not require the exception to catch and
handle.
Examples of Checked exceptions:
• FileNotFoundException
• NoSuchFieldException
• InterruptedException
• NoSuchMethodException
• ClassNotFoundException
Examples of Unchecked Exceptions:
• NoSuchElementException
• UndeclaredThrowableException
• EmptyStackException
• ArithmeticException
• NullPointerException
• ArrayIndexOutOfBoundsException
• SecurityException
Java Exception Keywords
Java provides five keywords that are used to handle the exception. The following table describes
each.
Keyword Description
try The "try" keyword is used to specify a block where we should place an exception code. It
means we can't use try block alone. The try block must be followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try block which
means we can't use catch block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the necessary code of the program. It is executed
whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an
exception in the method. It doesn't throw an exception. It is always used with method
signature.
Exception Mechanism:
Java try-catch block:
Java try block is used to enclose the code that might throw an exception. It must be used within the method.
If an exception occurs at the particular statement in the try block, the rest of the block code will not execute. So, it is
recommended not to keep the code in try block that will not throw an exception.
Java try block must be followed by either catch or finally block.
Syntax of Java try-catch
try
{
//code that may throw an exception
}
catch(Exception_class_Name ref)
{
}
Java catch block
Java catch block is used to handle the Exception by declaring the type of exception within the parameter. The
declared exception must be the parent class exception ( i.e., Exception) or the generated exception type. However,
the good approach is to declare the generated type of exception.
The catch block must be used after the try block only. You can use multiple catch block with a single try block.
The JVM firstly checks whether the exception is handled or not.
If exception is not handled, JVM provides a default exception
handler that performs the following tasks:
• Prints out exception description.
• Prints the stack trace (Hierarchy of methods where the
exception occurred).
• Causes the program to terminate.
But if the application programmer handles the exception, the
normal flow of the application is maintained, i.e., rest of the
code is executed.
Division by Zero:
public class Exception1
{
public static void main(String args[])
{
try
{
int data=100/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println(“GITAM");
}
}
public class TryCatchExample1
{
public static void main(String[] args)
{
int data=50/0; //may throw exceptio
n
System.out.println(“GITAM");
}
}
Problem without exception handling
Output::
Exception in thread "main" java.lang.ArithmeticException: / by zero
class Null_Pointer_Exception
{
public static void main(String args[])
{
String str = null;
System.out.println(str.length());
}
}
Output:
Exception in thread "main" java.lang.NullPointerException
at Null_Pointer_Exception.main(Null_Pointer_Exception.java:6)
NullPointerException:
ArrayIndexOutOfBoundsException:
public class Array_Index
{
public static void main(String[] args)
{
int[] a = {1, 2, 3};
System.out.println (a[10]);
System.out.println("GITAM");
}
}
Output: Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 4
at Array_Index.main(Array_Index.java:6)
public class Array_Index
{
public static void main(String[] args)
{
try
{
int[] a = {1, 2, 3};
System.out.println (a[10]);
}
System.out.println("GITAM");
}
}
public class Array_Index
{
public static void main(String[] args)
{
try
{
int[] a = {1, 2, 3};
System.out.println (a[10]);
}
catch (Exception e)
{
System.out.println("GITAM");
}
}
}
Array_Index.java:15: error: 'try' without 'catch', 'finally' or
resource declarations
Common Scenarios of Java Exceptions
There are given some scenarios where unchecked exceptions may occur. They are as follows:
1) A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0; //ArithmeticException
2) A scenario where NullPointerException occurs
If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
String s=null;
System.out.println(s.length()); //NullPointerException
3) A scenario where NumberFormatException occurs
If the formatting of any variable or number is mismatched, it may result into NumberFormatException.
Suppose we have a string variable that has characters; converting this variable into digit will cause
NumberFormatException.
String s="abc";
int i=Integer.parseInt(s); //NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException occurs
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be other reasons
to occur ArrayIndexOutOfBoundsException. Consider the following statements.
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
Java finally block:
In Java, the finally block is always executed no matter whether there is an exception or not. The finally block is
optional. And, for each try block, there can be only one finally block.
The basic syntax of finally block is:
try
{
//code
}
catch (ExceptionType1 e1)
{
// catch block
}
finally
{
// finally block always executes
}
If an exception occurs, the finally block is executed after the try...catch block. Otherwise, it is executed after
the try block. For each try block, there can be only one finally block
class Finally
{
public static void main(String[] args)
{
try
{
int a = 6 / 0;
}
catch (ArithmeticException e)
{
System.out.println(e.getMessage());
}
finally
{
System.out.println("This is the finally block");
}
}
}
Java Multi-catch block:
A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler.
So, if you have to perform different tasks at the occurrence of different exceptions, use java multi-catch block.
Points to remember
•At a time only one exception occurs and at a time only one catch block is executed.
•All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must come
before catch for Exception.
class Multi_Catch
{
public static void main(String[] args)
{
try
{
int a = 6/0;
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println(e.getMessage());
}
catch (ArithmeticException e)
{
System.out.println(e.getMessage());
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Throwing and Rethrowing an Exception:
Normally, catch block are used to handle the exceptions raised in the try block. The exception can re-
throw using throw keyword, if catch block is unable to handle it. This process is called as re-throwing an
exception. The Java throw keyword is used to throw an exception explicitly.
• If we throw unchecked exception from a method, it is must to handle the exception or declare in
throws clause.
• If we throw a checked exception using throw keyword, it is must to handle the exception using catch
block or the method must declare it using throws declaration.
public class ThrowDemo
{
public int test(int n1, int n2)
{
try
{
return n1/n2;
}
catch(ArithmeticException e)
{
throw e;
}
}
public static void main(String[] args)
{
ThrowDemo obj = new ThrowDemo();
try
{
System.out.println(obj.test(30, 0));
}
catch(Exception e)
{
System.out.println(e);
}
}
}
public class ThrowDemo1
{
public static void validate(int age)
{
if(age<18)
{
throw new ArithmeticException("Person is not eligible to vote");
}
else
{
System.out.println("Person is eligible to vote!!");
}
}
public static void main(String args[])
{
validate(13);
System.out.println("rest of the code...");
}
}
public class ThrowDemo2
{
static void test()
{
int x=6, y=0, z;
try
{
z = x/y ;
System.out.println(" I am in try block");
}
catch(ArithmeticException e)
{
throw e;
}
}
public static void main(String[] args)
{
try
{
test();
}
catch(ArithmeticException e)
{
System.out.println("Rethrown Exception Caught in main()");
System.out.println(e);
}
}
}
Java throws keyword
The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may
occur an exception. So, it is better for the programmer to provide the exception handling code so that the normal flow of
the program can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as
NullPointerException, it is programmers' fault that he is not checking the code before it being used.
Syntax of Java throws
return_type method_name() throws exception_class_name
{
//method code
}
Checked exception only be declared, because , Unchecked exception under our control so we can correct our code.
import java.io.IOException;
class ThrowsDemo
{
void m() throws IOException
{
throw new IOException("device error"); //checked exception
}
void n() throws IOException
{
m();
}
void p()
{
try
{
n();
}
catch(Exception e)
{
System.out.println("Exception Handled");
}
}
public static void main(String args[])
{
ThrowsDemo obj=new ThrowsDemo();
obj.p();
System.out.println("Normal Flow");
}
}

Exception Handling.pptx

  • 1.
    Exceptions in Java:Dictionary Meaning: Exception is an abnormal condition. Exception Handling in Java is one of the effective means to handle the runtime errors so that the regular flow of the application can be preserved. Java Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException etc. In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime. Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run time, that disrupts the normal flow of the program’s instructions. Exceptions can be caught and handled by the program. When an exception occurs within a method, it creates an object. This object is called the exception object. It contains information about the exception, such as the name and description of the exception and the state of the program when the exception occurred.
  • 2.
    Major reasons whyan exception Occurs • Invalid user input • Device failure • Loss of network connection • Physical limitations (out of disk memory) • Code errors • Opening an unavailable file • Error: Errors are problems that mainly occur due to the lack of system resources. It cannot be caught or handled. It indicates a serious problem. It occurs at run time. These are always unchecked. An example of errors is OutOfMemoryError, LinkageError, etc. are the subclasses of the Error class. • Exception: These are the errors that occur at compile time and run time. It occurs in the code written by the developers. It can be recovered by using the try-catch block and throws keyword. There are two types of exceptions i.e. checked and unchecked.
  • 3.
  • 4.
    Types of Exceptions Javadefines several types of exceptions that relate to its various class libraries. Java also allows users to define their own exceptions.
  • 5.
  • 6.
    1) Checked Exception Theclasses that directly inherit the Throwable class except RuntimeException and Error are known as checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at compile-time. 2) Unchecked Exception The classes that inherit the RuntimeException are known as unchecked exceptions. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime. 3) Error Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError, AssertionError etc.
  • 7.
    Checked Exception UncheckedException Checked exceptions occur at compile time. Unchecked exceptions occur at runtime. The compiler checks a checked exception. The compiler does not check these types of exceptions. These types of exceptions can be handled at the time of compilation. These types of exceptions cannot be a catch or handle at the time of compilation, because they get generated by the mistakes in the program. They are the sub-class of the exception class. They are runtime exceptions and hence are not a part of the Exception class. Here, the JVM needs the exception to catch and handle. Here, the JVM does not require the exception to catch and handle. Examples of Checked exceptions: • FileNotFoundException • NoSuchFieldException • InterruptedException • NoSuchMethodException • ClassNotFoundException Examples of Unchecked Exceptions: • NoSuchElementException • UndeclaredThrowableException • EmptyStackException • ArithmeticException • NullPointerException • ArrayIndexOutOfBoundsException • SecurityException
  • 8.
    Java Exception Keywords Javaprovides five keywords that are used to handle the exception. The following table describes each. Keyword Description try The "try" keyword is used to specify a block where we should place an exception code. It means we can't use try block alone. The try block must be followed by either catch or finally. catch The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later. finally The "finally" block is used to execute the necessary code of the program. It is executed whether an exception is handled or not. throw The "throw" keyword is used to throw an exception. throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the method. It doesn't throw an exception. It is always used with method signature.
  • 9.
  • 10.
    Java try-catch block: Javatry block is used to enclose the code that might throw an exception. It must be used within the method. If an exception occurs at the particular statement in the try block, the rest of the block code will not execute. So, it is recommended not to keep the code in try block that will not throw an exception. Java try block must be followed by either catch or finally block. Syntax of Java try-catch try { //code that may throw an exception } catch(Exception_class_Name ref) { }
  • 11.
    Java catch block Javacatch block is used to handle the Exception by declaring the type of exception within the parameter. The declared exception must be the parent class exception ( i.e., Exception) or the generated exception type. However, the good approach is to declare the generated type of exception. The catch block must be used after the try block only. You can use multiple catch block with a single try block. The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM provides a default exception handler that performs the following tasks: • Prints out exception description. • Prints the stack trace (Hierarchy of methods where the exception occurred). • Causes the program to terminate. But if the application programmer handles the exception, the normal flow of the application is maintained, i.e., rest of the code is executed.
  • 12.
    Division by Zero: publicclass Exception1 { public static void main(String args[]) { try { int data=100/0; } catch(ArithmeticException e) { System.out.println(e); } System.out.println(“GITAM"); } } public class TryCatchExample1 { public static void main(String[] args) { int data=50/0; //may throw exceptio n System.out.println(“GITAM"); } } Problem without exception handling Output:: Exception in thread "main" java.lang.ArithmeticException: / by zero
  • 13.
    class Null_Pointer_Exception { public staticvoid main(String args[]) { String str = null; System.out.println(str.length()); } } Output: Exception in thread "main" java.lang.NullPointerException at Null_Pointer_Exception.main(Null_Pointer_Exception.java:6) NullPointerException:
  • 14.
    ArrayIndexOutOfBoundsException: public class Array_Index { publicstatic void main(String[] args) { int[] a = {1, 2, 3}; System.out.println (a[10]); System.out.println("GITAM"); } } Output: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at Array_Index.main(Array_Index.java:6) public class Array_Index { public static void main(String[] args) { try { int[] a = {1, 2, 3}; System.out.println (a[10]); } System.out.println("GITAM"); } } public class Array_Index { public static void main(String[] args) { try { int[] a = {1, 2, 3}; System.out.println (a[10]); } catch (Exception e) { System.out.println("GITAM"); } } } Array_Index.java:15: error: 'try' without 'catch', 'finally' or resource declarations
  • 15.
    Common Scenarios ofJava Exceptions There are given some scenarios where unchecked exceptions may occur. They are as follows: 1) A scenario where ArithmeticException occurs If we divide any number by zero, there occurs an ArithmeticException. int a=50/0; //ArithmeticException 2) A scenario where NullPointerException occurs If we have a null value in any variable, performing any operation on the variable throws a NullPointerException. String s=null; System.out.println(s.length()); //NullPointerException
  • 16.
    3) A scenariowhere NumberFormatException occurs If the formatting of any variable or number is mismatched, it may result into NumberFormatException. Suppose we have a string variable that has characters; converting this variable into digit will cause NumberFormatException. String s="abc"; int i=Integer.parseInt(s); //NumberFormatException 4) A scenario where ArrayIndexOutOfBoundsException occurs When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be other reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements. int a[]=new int[5]; a[10]=50; //ArrayIndexOutOfBoundsException
  • 17.
    Java finally block: InJava, the finally block is always executed no matter whether there is an exception or not. The finally block is optional. And, for each try block, there can be only one finally block. The basic syntax of finally block is: try { //code } catch (ExceptionType1 e1) { // catch block } finally { // finally block always executes } If an exception occurs, the finally block is executed after the try...catch block. Otherwise, it is executed after the try block. For each try block, there can be only one finally block
  • 18.
    class Finally { public staticvoid main(String[] args) { try { int a = 6 / 0; } catch (ArithmeticException e) { System.out.println(e.getMessage()); } finally { System.out.println("This is the finally block"); } } }
  • 19.
    Java Multi-catch block: Atry block can be followed by one or more catch blocks. Each catch block must contain a different exception handler. So, if you have to perform different tasks at the occurrence of different exceptions, use java multi-catch block. Points to remember •At a time only one exception occurs and at a time only one catch block is executed. •All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must come before catch for Exception.
  • 20.
    class Multi_Catch { public staticvoid main(String[] args) { try { int a = 6/0; } catch (ArrayIndexOutOfBoundsException e) { System.out.println(e.getMessage()); } catch (ArithmeticException e) { System.out.println(e.getMessage()); } catch(Exception e) { System.out.println("Parent Exception occurs"); } System.out.println("rest of the code"); } }
  • 21.
    Throwing and Rethrowingan Exception: Normally, catch block are used to handle the exceptions raised in the try block. The exception can re- throw using throw keyword, if catch block is unable to handle it. This process is called as re-throwing an exception. The Java throw keyword is used to throw an exception explicitly. • If we throw unchecked exception from a method, it is must to handle the exception or declare in throws clause. • If we throw a checked exception using throw keyword, it is must to handle the exception using catch block or the method must declare it using throws declaration.
  • 22.
    public class ThrowDemo { publicint test(int n1, int n2) { try { return n1/n2; } catch(ArithmeticException e) { throw e; } } public static void main(String[] args) { ThrowDemo obj = new ThrowDemo(); try { System.out.println(obj.test(30, 0)); } catch(Exception e) { System.out.println(e); } } }
  • 23.
    public class ThrowDemo1 { publicstatic void validate(int age) { if(age<18) { throw new ArithmeticException("Person is not eligible to vote"); } else { System.out.println("Person is eligible to vote!!"); } } public static void main(String args[]) { validate(13); System.out.println("rest of the code..."); } }
  • 24.
    public class ThrowDemo2 { staticvoid test() { int x=6, y=0, z; try { z = x/y ; System.out.println(" I am in try block"); } catch(ArithmeticException e) { throw e; } } public static void main(String[] args) { try { test(); } catch(ArithmeticException e) { System.out.println("Rethrown Exception Caught in main()"); System.out.println(e); } } }
  • 25.
    Java throws keyword TheJava throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception. So, it is better for the programmer to provide the exception handling code so that the normal flow of the program can be maintained. Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as NullPointerException, it is programmers' fault that he is not checking the code before it being used. Syntax of Java throws return_type method_name() throws exception_class_name { //method code } Checked exception only be declared, because , Unchecked exception under our control so we can correct our code.
  • 26.
    import java.io.IOException; class ThrowsDemo { voidm() throws IOException { throw new IOException("device error"); //checked exception } void n() throws IOException { m(); } void p() { try { n(); } catch(Exception e) { System.out.println("Exception Handled"); } } public static void main(String args[]) { ThrowsDemo obj=new ThrowsDemo(); obj.p(); System.out.println("Normal Flow"); } }