Professional Documents
Culture Documents
(PCMC1050T)
Prof. Priya Kardile
Unit-V - Exception Handling
Exception handling fundamentals
exception types
uncaught exceptions
using try and catch
Throw
Throws
Finally
Java’s built-in exceptions
creating your own exceptions
Exception Handling
Exception handling fundamentals:-
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.
Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at
runtime.
Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException,
SQLException, RemoteException, etc.
The core advantage of exception handling is to maintain the normal flow of the application.
Eg
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Exception Handling
Exception handling fundamentals:-
Suppose there are 10 statements in a Java program and an exception occurs at
statement 5; the rest of the code will not be executed, i.e., statements 6 to 10 will
not be executed. However, when we perform exception handling, the rest of the
statements will be executed. That is why we use exception handling in java.
Hierarchy of Java Exception classes
The java.lang.Throwable class is the root class of Java Exception hierarchy inherited
by two subclasses: Exception and Error. The hierarchy of Java Exception classes is
given below:
Exception Handling
Diagram:
Exception Handling
Type of Exception:-
Java defines several types of exceptions that relate to its various class libraries. Java also allows users to
define their own exceptions.
Exception Handling
Checked Exception:-
These are the exceptions that are checked at compile time. If some code within a method throws a
checked exception, then the method must either handle the exception or it must specify the
exception using the throws keyword.
Unchecked Exception:-
These are the exceptions that are not checked at compile time.
The compiler will not check these exceptions at compile time. In simple words, if a program throws an
unchecked exception, and even if we didn’t handle or declare it, the program would not give a
compilation error.
User define Exception:-
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases,
users can also create exceptions, which are called ‘user-defined Exceptions’.
The advantages of Exception Handling in Java are as follows:
Provision to Complete Program Execution
Easy Identification of Program Code and Error-Handling Code
Propagation of Errors
Meaningful Error Reporting
Identifying Error Types
Exception Handling
Uncaught Exception:-
In java, assume that, if we do not handle the exceptions in a program. In this case,
when an exception occurs in a particular function, then Java prints a exception
message with the help of uncaught exception handler.
The uncaught exceptions are the exceptions that are not caught by the compiler but
automatically caught and handled by the Java built-in exception handler.
Java programming language has a very strong exception handling mechanism. It allow
us to handle the exception use the keywords like try, catch, finally, throw, and throws.
When an uncaught exception occurs, the JVM calls a special private method
known dispatchUncaughtException( ), on the Thread class in which the exception
occurs and terminates the thread.
The Division by zero exception is one of the example for uncaught exceptions. Look at
the following code.
Exception Handling
Uncaught Exception:-
import java.util.Scanner;
public class demo {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
System.out.println("Enter the a and b values: ");
int a = read.nextInt();
int b = read.nextInt();
int c = a / b;
System.out.println(a + "/" + b +" = " + c);
}
}
In the above example code, we are not used try and catch blocks, but when the value of b
is zero the division by zero exception occurs and it caught by the default exception
handler.
Exception Handling
Using try and catch Exception:-
The try statement allows you to define a block of code to be tested for errors while it
is being executed.
The catch statement allows you to define a block of code to be executed, if an error
occurs in the try block.
Syntax:-
try
{
//block of code
}catch(Exception e)
{
//block of code
}
Eg
public class Main {
public static void main(String[ ] args) {
int myNumbers[] = {1, 2, 3};
System.out.println(myNumbers[10]); // error! } }
Exception Handling
Using try and catch Exception:-
Eg
public class Main {
public static void main(String[ ] args) {
try {
int myNumbers[] = {1, 2, 3};
System.out.println(myNumbers[10]);
}catch(Exception e)
{
System.out.println(“Something went wrong”);
}
}
}
Exception Handling
Using try and catch Exception:-
public class demo {
public static void main(String[] args) {
try {
int list[] = new int[5];
list[2] = 10;
list[4] = 2;
list[10] = 10 / 2;
}catch(ArithmeticException ae) {
System.out.println("Problem info: Value of divisor can not be ZERO.");
}catch(ArrayIndexOutOfBoundsException aie) {
System.out.println("Problem info: ArrayIndexOutOfBoundsException has occured.");
}catch(Exception e) {
System.out.println("Problem info: Unknown exception has occured.");
}
//System.out.println("done");
}
}
Exception Handling
Throw and Throws:-
throw and throws keywords are used for exception handling, in which the former is used for throwing
exceptions explicitly while the latter is used as a signature for methods.
The Throw and Throws in Java are two keywords that can be used to do exception handling.
Throw: The Throw keyword in java is used to explicitly throw an exception inside a method or a block
of code in a java program.
Throws: The Throws keyword in java is used at the method signature to declare all the exceptions
that might be thrown by the method during its execution.
Syntax:
Throw: The syntax of the throw keyword is, keyword throw followed by the instance of the exception
that needs to be raised.
Below is the syntax: throw <instance>;
Eg. throw new IoException();
Syntax:
Throws: The syntax of the throws keyword is, keyword throws followed by class names of the
exceptions.
Below is the Syntax: Access_modifier return_type method_name() throws ExceptionType1,
ExceptionType2,….{ }
Exception Handling
Throw and Throws:-
Eg. public void test_method() throws ArithmaticException, NullPointerException{
// code or ststement
}
Exception Handling
Program(throw) :
//Using Throw keyword to handle UnChecked Exception
import java.io.*;
class demo {
public static void main(String[] args) {
try {
String temp = null;
if (temp == null) //Manually throwing the nullpointerexception
{
throw new NullPointerException("Temp is set to null");
} else {
System.out.println("String is " + temp);
}
} catch (NullPointerException e) {
System.out.println(e);
}
}
}
Output: java.lang.NullPointerException: Temp is set to null
Exception Handling
Program(throws) :
// Using Throws keyword to handle Checked Exception
import java.io.*;
class demo {
//Using throws keyword to handle the exception which might arise
public static void main(String[] args) throws FileNotFoundException {
try {
//reading a file from a path may throw FileNotFoundException
File file1 = new File("sample.txt");
FileInputStream f_stream = new FileInputStream(file1);
} catch (FileNotFoundException e) {
System.out.println(e);
}
}
}
Output: java.io.FileNotFoundException: sample.txt (The system cannot find the file specified)
Exception Handling
Difference Between Throw and Throws in Java Explained
Topic throw keyword throws keyword
Throw keyword in Java is mainly used for Throws keyword in Java is mainly used for declaring
Definition throwing exceptions explicitly at the time of known possible exceptions that can occur at the time
program execution. of program execution.
Usage It is used within the method definition. It is used with method declaration.
It is followed by the class name of Exceptions which is
Syntax It is followed by throwable objects.
going to be thrown.
Occurrence of Whenever system encounters a throw Whenever system encounters throws keyword, it
Exception keyword, it throws the exception explicitly. throws exception only when it actually occurs
Exception Handling
Finally keyword:
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.
Why use Java finally block?
finally block in Java can be used to put "cleanup" code such as closing a file, closing
connection, etc.
The important statements to be printed can be placed in the finally block.
Exception Handling
Finally keyword Program:
java.lang.ArithmeticException: / by zero
ClassNotFoundException
1
Class not found.
CloneNotSupportedException
2 Attempt to clone an object that does not implement the
Cloneable interface.
IllegalAccessException
3
Access to a class is denied.
InstantiationException
4
Attempt to create an object of an abstract class or interface.
InterruptedException
5
One thread has been interrupted by another thread.
NoSuchFieldException
6
A requested field does not exist.
NoSuchMethodException
7
A requested method does not exist.
Built in Exception
following is the list of Java Unchecked Runtime Exception.