0% found this document useful (0 votes)
14 views

Exception Handling

Uploaded by

Bhavish Jain
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Exception Handling

Uploaded by

Bhavish Jain
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 58

Exception Handling

Dr Richa
Assistant Professor
Introduction
• Types of Error
• Syntax Error
• Logical Error
• Runtime Error
Introduction
• The Exception Handling in Java is one of the powerful mechanism to
handle the runtime errors so that the normal flow of the application
can be maintained.
Syntax Error
• The syntax error occurs where some mistakes are done by
programmer, syntactic or grammatical mistakes.
Logical Error
• If a program is not giving as expected results, these kind of error is known
as logical error.
• Example: r=-b/2a; //it will not give any error but it will b=also not give
expected error.
• It should be r=-b/(2*a)
• Another example is
for(i=1;i<Arr.length.i++)
{
System.out.println(A[i]);
}
Runtime Error
• It occurs due to the mishandling of the program, user is not using the
program the way it should be.
• Runtime error occurs at the users end and the cause of error are
• Bad input
• Unavailability of resources.
• In both cases program will crash
• One major problem with runtime error is program will crash
• In case of this situation we need to tell the user that you have done so
and so mistake by using appropriate message.
• Programmer should do the arrangement in the program itself
Exception Handling Construct
Class Test
{
public static void main(String args[])
{
int a,b,c;
a=5;
b=0;
c=a/b;//result is infinity
System.out.println(c);
System.out.println(“End of program”);
}
}
Try catch Syntax
try
{
//code that may throw an exception
}
catch(Exception_class_Name ref)
{
//msg to the user if exception occurs
}
Variation of try and catch
• try with multiple catch
• Nested try catch
• Customized message in catch block
Try and catch block
public class Main
public static void main(String[] args)
int a,b,c;
try
{
a=10;
b=0;
c=a/b;
System.out.println("Result "+c);
}
catch(ArithmeticException e)
{
System.out.println("Division by zero error ");
}
System.out.println("Bye");
}
}
public class Main
public static void main(String[] args)
int a,b,c;
Scanner sc=new Scanner(System.in);
System.out.println("Enter 2 number ");
a=sc.nextInt();
b=sc.nextInt();
try {
c=a/b;
System.out.println("Result "+c);
}
catch(ArithmeticException e) {
System.out.println("Denominator can not be zero ");
}
System.out.println("Bye");
}
}
Nested Catch
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
int A[]={30,20,10,40,0};
int c=A[0]/A[1];
System.out.println("Division is"+c);
System.out.println(A[5]);
}
}
Multiple Catch
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
int A[]={30,20,10,40,0};
try {
int c=A[0]/A[1];
System.out.println("Division is"+c);
System.out.println(A[5]);
}
catch(ArithmeticException e) {
System.out.println("Denominator should not be 0");
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Index out of bounds exception");
}
System.out.println("Bye");
}
}
Various Scenario
• What if two exceptions occurs simultaneously?
• What if the exact exception class is not present in catch argument?
Exception
class
• In java, exceptions are mainly categorized into two types, and they are
as follows.
• Checked Exceptions
• Unchecked Exceptions
• The checked exception is an exception that is checked by the compiler
during the compilation process to confirm whether the exception is
handled by the programmer or not. If it is not handled, the compiler
displays a compilation error using built-in classes.
• The following are a few built-in classes used to handle checked
exceptions in java.
• IOException
• FileNotFoundException
• ClassNotFoundException
• SQLException
• DataAccessException
• InstantiationException
• UnknownHostException
• The unchecked exception is an exception that occurs at the time of
program execution. The unchecked exceptions are not caught by the
compiler at the time of compilation.
• The unchecked exceptions are generally caused due to bugs such as
logic errors, improper use of resources, etc.
• ArithmeticException
• NullPointerException
• NumberFormatException
• ArrayIndexOutOfBoundsException
• StringIndexOutOfBoundsException
Nested try catch block
Try
{
try
{
}
catch(Exception e)
{
}
}
Catch(Exception e)
{
}
Finally Block
• Java finally block is always executed whether an
exception is handled or not.
• If you don't handle the exception, before
terminating the program, JVM executes finally
block (if any).
• When an exception does not occur
• When an exception occur but not handled by the catch block
• When an exception occurs and is handled by the catch block
Example
public class Main
{
public static void main(String[] args)
{
try
{
int a=5,b=0,c;
c=a/b;
}
catch(Exception e)
{
System.out.print("msg: "+e);
}
finally
{
System.out.print("msg from finally: ");
}
}
}
Point to remember
• For each try block there can be only one finally block.
• The finally block will not be executed if the program exits (either
by calling System.exit() or by causing a fatal error that causes
the process to abort).
Nested try Example
Exception Propagation
• If the exception occurs in one method is not handled at suitable point
then it will be transmitted to the calling method as well.
• If calling method has also not handled the exception then it will
further propagate to main as well.
• printStackTrace will help you to track the propagation
public class Main{
public static void m() {
int arr[]={1,2,3};
System.out .println("arr[4]: "+arr[4]);
}
static void n() {
try{
m();
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Index over reached");
}
} c
public static void main(String[] args) {
n();
}
}
Throw Exception
• Consider a method where we need to compute the area of rectangle.
• If(length<0 || breadth<0)
throw new Exception(“length and breadth can not be -ve”)

Exception is a built-in class and we are throwing object of exception class with a message.
Since it’s a checked exception so we need to handle it. It will not be handled by compiler.
First of all it should be at the same place where we have thrown and catch at the same
place
The purpose is to throw it to the calling method
If we are not handling in the same line then we declare in the signature that this method
throws exception
Throws
int area( int l, int b) throws Exception

throw is a verb (action)


throws is a continuous tense and acting as an objective
That means whoever is calling this method area() method should handle the exception, so it comes
inside the signature and will be catch by the calling method
Try
{
area()
}
catch(Exception e){}
If you do not want to handle it at this point then whoever calling this method who contains this
portion will use try and catch to handle the catched exception
• If you do not give the try and catch in main then the program will not
be compiled
Example throw
public class Main
{
public static void validate(int length,int breadth)
{
if(length<0 ||breadth<0)
{
throw new ArithmeticException("length can not less than zero");
}
else
{
int area= length*breadth;
System.out.println("area: "+area);
}
}
public static void main(String[] args) {
validate(-10,9);
}
}
• we can also throw unchecked and user defined exceptions.
• If we throw unchecked exception from a method, it is must to
handle the exception or declare in throws clause.
Example
public class Main
{
public static void validate(int length,int breadth) throws ArithmeticException
{
int c=length/breadth;
throw new ArithmeticException();
}
public static void main(String[] args)
{
try
{
validate(10,0);
}
catch(Exception e)
{
System.out.println("Numerator can not be zero");
}
}
Throwing User-defined Exception
class NegativeDimension extends Exception{
public String toString() {
return "Dimension can not be negative";
}
}
public class Main{
public static void validate(int length,int breadth) throws NegativeDimension
{
if(length<0 || breadth<0) {
throw new NegativeDimension(); try
{
} validate(-10,10);
else }
{ catch(NegativeDimension e)
System.out.println("area is: "+(length*breadth));
System.out.println(e);
}
}
} }
public static void main(String[] args) { }
Throwing User-defined Exception
class Myexception extends Exception{
public Myexception(String s) {
super(s);
}
}
public class Main{
public static void main(String[] args) {
try {
throw new Myexception("Myexception class");
}
catch(Exception e) {
System.out.println("exception caught"+e.getMessage());
}
}
}
Throwing User-defined Exception
class InvalidAgeException extends Exception{
public InvalidAgeException(String str) {
super(str);
}
}
public class Main{
static void vaildate(int age) throws InvalidAgeException {
if(age<0)
throw new InvalidAgeException("Age in invalid");
}
public static void main(String[] args) {
try {
vaildate(-9);
} catch(InvalidAgeException e) {
System.out.println("exception caught"+e.getMessage());
}
}
}
Throwing User-defined Exception
class InvalidAgeException extends Exception{
public String toString() {
return "Exception in InvalidAgeException";
}
}
public class Main{
static void vaildate(int age) throws InvalidAgeException {
if(age<0)
throw new InvalidAgeException();
}
public static void main(String[] args) {
try {
vaildate(-9);
}
catch(InvalidAgeException e) {
System.out.println(e);
}
}
}
• Create a method1 that computes the division operation on two
constant values. Create another method named method2() that calls
method1() and similarly method3() that calls method2(). In the main()
function call method3() and see the result if exception occurs in
method1(). Now create a try and catch block to handle the exception
occurred in method using pre-defined methods of exception.
Chained exception
• A technique that enables programmers to associate one Exception with
another.
• A chained exception is created by wrapping an existing exception in a
new exception, which becomes the root cause of the new Exception.
• A chained exception is created using one of the constructors of the
exception class.
• Constructors and methods for supporting chained exceptions are
available in the Throwable class. Let's start by taking a look at the
constructors.
• Throwable(Throwable cause): A Java constructor creates a new
exception object with a specified cause exception.
• Throwable(String desc, Throwable cause): A Java constructor
creates a new Throwable object with a message and a cause. It allows
for chaining exceptions and providing more detailed information about
errors.
• getCause(): It is a Java method of the Throwable class that returns the
cause of the current Exception. It allows for accessing the Exception
or error that triggered the current Exception to be thrown.
• initCause() method: determines the reason for the calling Exception.
Example without chained exception
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int num = scanner.nextInt();
scanner.close();
try {
if (num < 0) {
throw new IllegalArgumentException("Number must be positive");
}
int result = 100 / num;
System.out.println("Result: " + result);
}
catch (IllegalArgumentException e) {
System.out.println("Invalid input: " + e.getMessage());
}
catch (ArithmeticException e) {
System.out.println("Error: division by zero");
}
}
Chained Exception
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int num = scanner.nextInt();
scanner.close();
try {
if (num < 0) {
throw new IllegalArgumentException("Number must be positive");
}
int result = 100 / num;
System.out.println("Result: " + result);
}
catch (IllegalArgumentException e) {
throw new RuntimeException("Invalid input", e);
}
catch (ArithmeticException e) {
throw new RuntimeException("Error: division by zero", e);
}
}
Why Chained Exception
• Particularly useful in large programs or complex systems where
exceptions can be thrown across different components, as it can help
identify where the problem first occurred and how it propagated
through the system.
• Chained exceptions provide more context to the Exception and make it
easier to identify and fix the root cause of the problem.
• The original cause of the Exception is preserved and reported along
with the current Exception.
Throw and throws
• throw keyword in java is used to throw an exception explicitly.
• We can throw checked as well as unchecked exceptions (compile-time and runtime) using it.
• We specify the class of exception object which is to be thrown. The exception has some error message with it
that provides the error description.
• We can also define our own set of conditions for which we can throw an exception explicitly using the throw
keyword.
• The flow of execution of the program stops immediately after the throw statement is executed and the
nearest try block is checked to see if it has a catch statement that matches the type of exception.
• It tries to find all the catch blocks until it finds the respective handler, else it transfers the control to the
default handler which will halt the program.
throws
• throws keyword in java is used in the signature of the method to indicate that this method might throw one of
the exceptions from java exception class hierarchy.
• throws keyword is used only for checked exceptions like IOException as using it with unchecked exceptions is
meaningless(Unchecked exceptions can be avoided by correcting the programming mistakes.)
Methods in Exception
• printStackTrace(): print the exception in the format of : exception
declaration and stack trace
• toString(): Name of the exception and exception description
• getMessage(): only description of exception
Try with Resources
• Resources?
• Why finally?
• Try with Resources
• Try with resources has been added java7 onwards
Why Resources
• Releasing the resources is important if the program need the
resources outside the program.
• Heap memory is automatically collected in java using GC but for the
rest programmer should close the resources.
• Otherwise it will not be able to used by other programs.
Why finally
Int method1() throws Exception
{
FileReader f=new Filereader(“my.txt”);
//use file
f.close();
return result;
}
The program will work perfectly if there is no exception but in case of exception
then it will not execute the last lines. It result into not closing the file that
means resources is not released. To get the cleanup done we will use finally
Modification
Int method1() throws Exception
{
FileReader f
try{
f=new Filereader(“my.txt”);
//use file
return result;
}
finally
{
f.close();
}
}
In case of exception it will first close the file and then it will throw an exception
Try with resources
Int method1() throws Exception
{
try(FileReader f=new FileReader(“myfile.txt”))
{
//use file
return result;
}
}
In the above case automatically after execution resource will be closed and we do not need
finally block.
Note: there is no need of catch block since we are throwing the exception in calling method.
• Multiple resources can be used in try with resources by separating
with each other using semicolon
Java Custom Exception
• Creating your own exception class
Assertion
• Assertion is a statement in java. It can be used to test your
assumptions about the program.
• While executing assertion, it is believed to be true. If it fails, JVM will
throw an error named AssertionError. It is mainly used for testing
purpose.
• assert expression;
• assert expression1 : expression2;
import java.util.Scanner;
class AssertionExample
{
public static void main( String args[] )
{
Scanner scanner = new Scanner( System.in );
System.out.print("Enter ur age ");

int value = scanner.nextInt();


assert value>=18:" Not valid";

System.out.println("value is "+value);
}
}
•Compile it by: javac AssertionExample.java
•Run it by: java -ea AssertionExample
Stack Unwinding
When an exception is thrown but not caught in a particular scope, the
method-call stack is "unwound," and an attempt is made to catch the
exception in the next outer try block. This process is called stack
unwinding. Unwinding the method-call stack means that the method in
which the exception was not caught terminates, all local variables in
that method go out of scope and control returns to the statement that
originally invoked that method. If a Try block encloses that statement, an
attempt is made to catch the exception. If a try block does not enclose that
statement, stack unwinding occurs again. If no catch block ever catches
this exception and the exception is checked, compiling the program will
result in an error.

You might also like