Exception Handling in
JAVA
Part-2
Instructor Name: Muhammad Fayyaz Awan
Department of Computer Science, COMSATS University Islamabad, Wah Campus, Pakistan
Outline
2
Recap
Terms used in Exception Handling
Common Scenarios where Exceptions may Occur
User defined Exceptions
References
Recap
3
• What
An exception is an event that alters the normal flow of the program.
Checked (compile time) and unchecked (runtime) exceptions.
An Error indicates serious problems, unchecked type, mostly occur at runtime
Exception handling is a framework that is used to handle runtime errors.
• Why
To maintain the normal flow of the application/program.
Terms used in Exception Handling
4
• Try-Catch: Piece of code of your program that you want to monitor for
exceptions are contained within a try block. If an exception occurs
within the try block, it is thrown. Catch block can catch this exception
and handle it in some logical manner.
• Finally: Any code that absolutely must be executed before a method
returns, is put in a finally block.
• Throw: System-generated exceptions are automatically thrown by the
Java run-time system. Now if we want to manually throw an exception,
we have to use the throw keyword.
Terms used in Exception Handling
5
• Throws: If a method is capable of causing an exception that it does not handle, it must
specify this behavior so that callers of the method can guard themselves against that
exception.
You do this by including a throws clause in the method’s declaration. Basically it is used
for IO Exception. A throws clause lists the types of exceptions that a method might
throw.
This is necessary for all exceptions, except those of type Error or Runtime Exception, or
any of their subclasses. All other exceptions that a method can throw must be declared
in the throws clause. If they are not , a compile-time error will result.
Exception Handling (try-catch example slide-1)
6
class ExceptionThrown // The runTime System searches the appropriate Exception handler
{ // in this method also but couldn't have found. So looking forward
// on the call stack.
// It throws the Exception(ArithmeticException). static int computeDivision (int a, int b)
// Appropriate Exception handler is not found within this {
method. int res =0;
try
static int divideByZero (int a, int b) {
{ res = divideByZero (a,b);
}
// this statement will cause ArithmeticException(/ by // doesn't matches with ArithmeticException
zero) catch (NumberFormatException ex)
int i = a/b; {
return i; System.out.println ("NumberFormatException is occured");
} }
return res;
}
Exception handling (try-catch example slide-2)
7
//main method
public static void main(String args[])
{
int a = 1;
int b = 0;
try
{
int i = computeDivision(a,b); Output:
}
// matching ArithmeticException
catch (ArithmeticException ex) Message String=/ by zero.
{
// getMessage will print description of exception(here / by zero)
System.out.println(“Message String=“ +ex.getMessage());
}
}
} This method is used to get the detail message of exception as a
string value.
Multi-Catch Block
8
public class TestMultipleCatchBlock
{ public static void main(String args[])
{
try At a time only one
Exception is occurred and
{ at a time only one catch
int a[]=new int[5]; block is executed.
a[5]=30/0;
} All catch blocks must be
catch (ArithmeticException e) ordered from most specific
{System.out.println("task1 is completed");} to most general i.e. catch
for ArithmeticException
catch (ArrayIndexOutOfBoundsException e) must come before catch for
{System.out.println("task 2 completed");} Exception .
catch (Exception e)
{System.out.println("common task
completed");}
System.out.println("rest of the code...");
}
}
Throw Keyword
9
• throw keyword is used to explicitly throw an exception from a method
or any block of code.
• throw either checked and unchecked exceptions.
• throw keyword is mainly used to throw custom exceptions.
Syntax
throw Instance
Example:
throw new ArithmeticException("/ by zero");
Throw Keyword (Example)
10
// Java program that demonstrates the use of throw //main method
class ThrowExcep public static void main(String args[])
{ {
static void fun() try
{
{
try
{
fun();
throw new NullPointerException("demo"); }
} catch(NullPointerException e)
catch (NullPointerException e) {
{ System.out.println("Caught in main.");
System.out.println("Caught inside fun()."); }
throw e; }
// re-throwing the exception
}
} } Output:
Caught inside fun().
Caught in main.
Throw Keyword (Example Explanation)
11
• The flow of execution of the program stops immediately after the throw statement is
executed and the nearest enclosing try block is checked to see if it has a catch
statement that matches the type of exception.
• If it finds a match, controlled is transferred to that statement otherwise next
enclosing try block is checked and so on.
• If no matching catch is found then the default exception handler will halt the
program.
Sequence of Events for throw
Preceding step
try block
throw
statement
unmatched catch
matching catch
unmatched catch
next step
Throws Keyword
13
• throws keyword is used in the signature of method to indicate
that this method might throw one of the listed type exceptions.
The caller to these methods has to handle the exception using a
try-catch block.
Syntax
type method_name(parameters) throws exception_list
exception_list is a comma separated list of all the exceptions which a method
might throw.
Throws Keyword
14
Scenario:
In any program, if there is a chance of rising an exception then compiler always warn us
about it and compulsorily we should handle that checked exception, Otherwise we will get
compile time error saying unreported exception XXX must be caught or declared to be
thrown. To prevent this compile time error we can handle the exception in two ways:
1.By using throws keyword
2.By using try catch
Unhandled Exception (Example)
15
//Java program to illustrate error in case
// of unhandled exception
class tst Output:
{ error: unreported exception InterruptedException;
must be caught or declared to be thrown
public static void main(String[] args)
{
Thread.sleep(10000);
System.out.println("Hello");
} Explanation : In this program, we are getting compile time error
because there is a chance of exception if the main thread is going to
} sleep, other threads get the chance to execute main() method which
will cause InterruptedException.
Use of throws Keyword (Example)
16
// Java program to illustrate throws
class tst
{
public static void main(String[] args) throws InterruptedException
{
Thread.sleep(10000);
System.out.println(“Dear Students");
}
}
Explanation : In the above program, by using throws keyword we
Output: handled the InterruptedException and we will get the output as
Dear Students
Dear Students
Throws Keyword (Using try-catch)
17
// Java program to demonstrate working of throws
class ThrowsExecp
{
static void fun() throws IllegalAccessException
{
System.out.println("Inside fun(). ");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
try
Ouput:
{
Inside fun().
fun();
caught in main.
}
catch(IllegalAccessException e)
{
System.out.println("caught in main.");
}
}
}
Finally Block
18
• The finally keyword is used in association with a try-catch block and
guarantees that a section of code will be executed, even if an exception
is thrown.
• The finally block will be executed after the try and catch blocks, but
before control transfers back to its origin.
• finally block will execute whether an exception occurs or not or
whether corresponding catch block found or not.
Finally Block (Example-1)
19
// Java program to illustrate finally in // Case where exceptions do not // occur in the program
class B
{
t he p rogram
public static void main(String[] args)
o no t o ccur in
ns d
{ Exceptio
int k = 55;
try
{
System.out.println("In try block");
int z = k / 55;
Output:
}
In try block
catch (ArithmeticException e) Executes whether exception occurs or not
{
System.out.println("In catch block");
System.out.println("Dividing by zero but caught");
}
finally
{
System.out.println("Executes whether exception occurs or not");
}
}
}
Finally Block (Example-2)
20
// Java program to illustrate finally // Case where exceptions occur // and match in the program
class C
{ s po nding
public static void main(String[] args) an d corre
n o cc urs
{
Ex c eptio m atches
int k = 66;
a tch block
try { c
System.out.println("In try block");
int z = k / 0;
// Carefully see flow dosen't come here
System.out.println("Flow dosen't came here");
}
Output:
catch (ArithmeticException e) {
System.out.println("In catch block"); In try block
System.out.println("Dividing by zero but caught"); In catch block
} Dividing by zero but caught
Finally block, Executes whether an exception occurs or not
finally
{
System.out.println(“Finally block, Executes whether an exception occurs or not");
}
}
}
Common Scenarios where Exceptions may Occur
ArithmeticException occurs
int a=50/0; //ArithmeticException
NullPointerException occurs
String s=null;
System.out.println(s.length()); //NullPointerException
NumberFormatException occurs
String s="abc";
int i=Integer.parseInt(s); //NumberFormatException
ArrayIndexOutOfBoundsException occurs
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
User-defined Exceptions
If we can create your own exceptions in Java. Then, keep the following points in mind when writing your
own exception classes.
• All exceptions must be a child of Throwable.
• If you want to write a checked exception that is automatically enforced by the Handle or Declare
Rule, you need to extend the Exception class.
• If you want to write a runtime exception, you need to extend the RuntimeException class.
• For example, we can define our own Exception class as below: class MyException extends Exception{ }
User-defined Exception (Example)
/* This is my Exception class, I have named it MyException * you class Example1
can give any name, just remember that it should * extend {
Exception class */ public static void main(String args[])
{
class MyException extends Exception
try
{
String str1; { System.out.println("Starting of try block");
/* Constructor of custom exception class * here I am copying // I'm throwing the custom exception using throw
the message that we are passing while * throwing the throw new MyException("This is My error Message");
exception to a string and then displaying * that string along }
with the message. */ catch(MyException exp)
{
MyException(String str2) System.out.println("Catch Block") ;
{ str1=str2; }
System.out.println(exp) ;
public String toString()
{ return ("MyException Occurred: "+str1) ; } }
} } Output:
} Starting of try block
Catch Block
MyException Occurred: This is My error
Message
References
24
• https://www.geeksforgeeks.org/exceptions-in-java/
• https://www.geeksforgeeks.org/checked-vs-unchecked-exceptions-in-java/
• https://www.geeksforgeeks.org/throw-throws-java/
• https://www.geeksforgeeks.org/types-of-exception-in-java-with-examples/
• https://beginnersbook.com/2013/04/java-checked-unchecked-exceptions-with-examples/
• https://www.journaldev.com/1696/exception-handling-in-java
• https://www.geeksforgeeks.org/g-fact-24-finalfinally-and-finalize-in-java/