Unit3 First Half
Unit3 First Half
• 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.
Java Exception Keywords
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.
Java Exception Handling Example
Output:
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
Solution by exception handling
Example1
try{
int a[]=new int[5];
Output:
System.out.println(a[10]); ArrayIndexOutOfBounds Exception occurs
} rest of the code
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Example 3
System.out.println("normal flow..");
}
}
Output:
• When any try block does not have a catch block for
a particular exception, then the catch block of the
outer (parent) try block are checked for that
exception, and if it matches, the catch block of
outer try block is executed.
• If none of the catch block specified in the code is
unable to handle the exception, then the Java
runtime system will handle the exception. Then it
displays the system generated message for that
exception
Java finally block