Chapter 1 - Unit 3
Chapter 1 - Unit 3
Chapter 1 - Unit 3
Exception Handling
1) Checked Exception
Checked exceptions are checked at compile-time.
The classes that directly inherit the Throwable class except
RuntimeException and Error are known as checked exceptions.
For example, IOException, SQLException, etc.
2) Unchecked Exception
Unchecked exceptions are not checked at compile-time, but they are
checked at runtime.
The classes that inherit the RuntimeException are known as unchecked
exceptions.
For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc.
3) Error
Error is irrecoverable.
Some example of errors are OutOfMemoryError, VirtualMachineError,
AssertionError etc.
Exception Keywords
Java provides five keywords that are used to handle the exception. The
following table describes each.
Keyword Description
ClassExceptionExample
{
public static void main(String args[])
{
try
{
int data=100/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code...");
}
}
OUTPUT :
try-catch block
try block
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.
try block must be followed by either catch or finally block.
Syntax of try-catch
try
{
//code that may throw an exception
}
catch(Exception_class_Name ref)
{
}
Syntax of try-finally block
try
{
//code that may throw an exception
}
finally
{
}
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:
o Prints out exception description.
o Prints the stack trace (Hierarchy of methods where the exception
occurred).
o 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.
As displayed in the above example, the rest of the code is not executed (in
such case, the rest of the code statement is not printed).
There might be 100 lines of code after the exception. If the exception is not
handled, all the code below the exception won't be executed.
Solution by exception handling
Let's see the solution of the above problem by a java try-catch block.
class TryCatchExample2
{
public static void main(String[] args)
{
try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
As displayed in the above example, the rest of the code is executed, i.e., the rest of the
code statement is printed.
Example 3
Example 1
Let's see a simple example of java multi-catch block.
MultipleCatchBlock1.java
class MultipleCatchBlock1
{
public static void main(String[] args)
{
try
{
int a[]=new int[5];
a[5]=30/0;
}
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 2
Let's see a simple example of java multi-catch block.
MultipleCatchBlock2.java
class MultipleCatchBlock2
{
public static void main(String[] args)
{
try
{
int a[]=new int[5];
System.out.println(a[10]);
}
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
In this example, try block contains two exceptions. But at a time only one exception occurs and
its corresponding catch block is executed.
MultipleCatchBlock3.java
class MultipleCatchBlock3
{
public static void main(String[] args)
{
try
{
int a[]=new int[5];
a[5]=30/0;
System.out.println(a[10]);
}
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 4
In this example, we generate NullPointerException, but didn't provide the
corresponding exception type. In such case, the catch block containing the parent
exception class Exception will invoked.
MultipleCatchBlock4.java
class MultipleCatchBlock4
try
String s=null;
System.out.println(s.length());
catch(ArithmeticException e)
catch(ArrayIndexOutOfBoundsException e)
}
catch(Exception e)
Let's see an example where we place a try block within another try block for two
different exceptions.
class NestedTryBlock
{
public static void main(String args[])
{
//outer try block
try
{
//inner try block 1
try
{
System.out.println("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(e);
}
//inner try block 2
try
{
int a[]=new int[5];
//assigning the value out of array bounds
a[5]=4;
}
//catch block of inner try block 2
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement");
}
//catch block of outer try block
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
}
System.out.println("normal flow..");
}
}
Note :
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.
Example 2
Let's consider the following example. Here the try block within nested try
block (inner try block 2) do not handle the exception. The control is then
transferred to its parent try block (inner try block 1). If it does not handle the
exception, then the control is transferred to the main try block (outer try
block) where the appropriate catch block handles the exception. It is termed
as nesting.
NestedTryBlock2.java
class NestedTryBlock2
{
public static void main(String args[])
{
// outer (main) try block
try
{
//inner try block 1
try
{
// inner try block 2
try
{
int arr[] = { 1, 2, 3, 4 };
//printing the array element out of its bounds
System.out.println(arr[10]);
}
// to handles ArithmeticException
catch (ArithmeticException e)
{
System.out.println("Arithmetic exception");
System.out.println(" inner try block 2");
}
}
// to handle ArithmeticException
catch (ArithmeticException e)
{
System.out.println("Arithmetic exception");
System.out.println("inner try block 1");
}
}
// to handle ArrayIndexOutOfBoundsException
catch (ArrayIndexOutOfBoundsException e4)
{
System.out.print(e4);
System.out.println(" outer (main) try block");
}
catch (Exception e5)
{
System.out.print("Exception");
System.out.println(" handled in main try-block");
}
System.out.print("Rest of the code");
}
}
finally block
Java finally block is a block used to execute important code such as closing
the connection, etc.
Java finally block is always executed whether an exception is handled or not.
Therefore, it contains all the necessary statements that need to be printed
regardless of the exception occurs or not.
The finally block follows the try-catch block.
o Let's see the below example where the Java program does not throw any
exception, and the finally block is executed after the try block.
TestFinallyBlock.java
class TestFinallyBlock
{
public static void main(String args[])
{
Try
{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e)
{
System.out.println(e);
}
//executed regardless of exception occurred or not
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of phe code...");
}
}
Case 2: When an exception occurs but not handled by the catch block
o Let's see the following example. Here, the code throws an exception
however the catch block cannot handle it. Despite this, the finally block is
executed after the try block and then the program terminates abnormally.
TestFinallyBlocclass TestFinallyBlock1
try
int data=25/0;
System.out.println(data);
catch(NullPointerException e)
System.out.println(e);
}
Case 3: When an exception occurs and is handled by the catch block
Example:
o Let's see the following example where the Java code throws an exception
and the catch block handles the exception. Later the finally block is
executed after the try-catch block. Further, the rest of the code is also
executed normally.
try
int data=25/0;
System.out.println(data);
catch(ArithmeticException e)
System.out.println("Exception handled");
System.out.println(e);
}
//executes regardless of exception occured or not
finally
}
throw keyword
o The Java throw keyword is used to throw an exception explicitly.
o We specify the exception object which is to be thrown. The Exception has
some message with it that provides the error description. These exceptions
may be related to user inputs, server, etc.
o We can throw either checked or unchecked exceptions in Java by throw
keyword. It is mainly used to throw a custom exception. We will discuss
custom exceptions later in this section.
o We can also define our own set of conditions and throw an exception
explicitly using throw keyword. For example, we can throw
ArithmeticException if we divide a number by another number. Here, we
just need to set the condition and throw exception using throw keyword.
o The syntax of the Java throw keyword is given below.
o throw Instance i.e.,
TestThrow1.java
o In this example, we have created the validate method that takes integer
value as a parameter. If the age is less than 18, we are throwing the
ArithmeticException otherwise print a message welcome to vote.
class TestThrow1
{
//function to check if person is eligible to vote or not
public static void validate(int age)
{
if(age<18)
{
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else
{
System.out.println("welcome to vote!!");
}
}
//main method
public static void main(String args[])
{
//calling the function
validate(13);
System.out.println("rest of the code...");
}
}
throws keyword
o 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.
throws Example
o Let's see the example of Java throws clause which describes that checked exceptions
can be propagated by throws keyword.
import java.io.IOException;
class Testthrows1
{
m();
void p()
try{
n();
catch(Exception e)
System.out.println("exception handled");
obj.p();
System.out.println("normal flow...");
}
Difference between throw and throws in Java
o The throw and throws is the concept of exception handling where the throw keyword
throw the exception explicitly from a method or a block of code whereas the throws
keyword is used in signature of the method.
o There are many differences between throw and throws keywords. A list of differences
between throw and throws are given below:
throw Example
TestThrow.java
class TestThrow
//defining a method
if (num < 1)
else
//main method
obj.checkNum(-3);
}
}
throws Example 1:
TestThrows.java
class TestThrows
//defining a method
int div = m / n;
return div;
//main method
try
System.out.println(obj.divideNum(45, 0));
}
catch (ArithmeticException e)
Example 2:
TestThrows.java
class TestThrows
//defining a method
int div = m / n;
return div;
//main method
public static void main(String[] args)
try
System.out.println(obj.divideNum(45, 1));
catch (ArithmeticException e)
Syntax:
We do not have any particular syntax for Java user-defined exception;
we will see how to create a User-defined exception.
class SampleException
{
public static void main(String args[])
{
try
{
throw new UserException(<value>); // used to create new exception and throw
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class UserException extends Exception
{
// code for for exception class
}
Example 1 :
Note :
Example 2 :
class OwnException extends Exception
{
// Declare parameterized constructor with String as a parameter.
OwnException(String str)
{
super(str); // Call super exception class constructor.
}
}
class MyClass
{
public static void main(String[] args)
{
try
{
// Create an object of user defined exception and throw it using throw clause.
OwnException obj = new OwnException("Creating user defined exception");
throw obj;
// or, throw new OwnException("Creating user defined exception");
}
catch (OwnException ex)
{
System.out.println("Caught a user defined exception");
System.out.println(ex.getMessage());
//System.out.println(ex.getLocalizedMessage());
//System.out.println(ex.toString());
}
}
}
Example 3:
Let’s take an example program where we will evaluate candidate’s age to vote. If
the candidate’s age is less than 18 years, the program will throw a custom
exception “Invalid age”. See the program source code to understand better and
follow all steps.
import java.util.Scanner;
InvalidAgeException(String str)
{
super(str);
class MyClass
age = sc.nextInt();
if(age <18)
else
System.out.println("Welcome to vote");
try
validate();
}
catch(Exception e)
//System.out.println(e.getMessage());
//System.out.println(e.getLocalizedMessage());
System.out.println(e.toString());
Output - 1
Output - 2
Output - 3
}
toString() in Java
So what exactly is this method? Object class is the parent class in Java.
It contains the toString() method.
The toString() method is used to return a string representation of an object.
If any object is printed, the toString() method is internally invoked by the
java compiler.
Else, the user implemented or overridden toString() method is called.
Here are some of the advantages of using this method.
Advantage
If you override the toString() method of the Object class, it will return values of
the object, hence you are not required to write a lot of code.
Example For toString
Parameter(s):
It does not accept any parameter.
Return value:
The return type of the method is String, it represents string for the exception.
}
catch (Exception ex)
{
System.out.println("ex.toString() :" + ex.toString());
}
}
// This method divide number by 0
public static void div(int d1, int d2) throws Exception
{
int res = d1 / d2;
System.out.println("res :" + res);
}
}
Output 1:
1
Output 2:
ex.toString() :java.lang.ArithmeticException: / by zero