ExceptionHandling Part-2 (Week 4-2)
ExceptionHandling Part-2 (Week 4-2)
ExceptionHandling Part-2 (Week 4-2)
JAVA
Part-2
Recap
Terms used in Exception Handling
Common Scenarios where Exceptions may Occur
User defined Exceptions
References
Recap
3
• What
• Why
• 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.
• 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());
}
}
Syntax
throw Instance
Example:
throw new ArithmeticException("/ by zero");
Throw Keyword (Example)
10
• 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 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
Syntax
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:
• The finally block will be executed after the try and catch blocks, but
before control transfers back to its origin.
// 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.
• 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/