You are on page 1of 26

Java Programming

(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.

acess_modifier return_type method_name () throws


exception_type1, exception_type2, …,
Implementatio throw throwableObject;-> It allows throwing
exception_typeN {//Java_Code} ->We can declare
n only one exception at a time.
multiple exceptions separated by commas using the
throws keyword.

If we are using throw keyword, then we must


Exception If we are using throws keyword, then the calling
write appropriate catch blocks to handle
Handling method will handle the exception.
that exception.

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:

public class demo{


public static void main(String args[]){
try {
System.out.println("Inside try block");
//below code throws divide by zero exception
int data=25/0;
System.out.println(data);
} catch(ArithmeticException e){
System.out.println("Exception handled"); //handles the Arithmetic Exception / Divide by zero exception
System.out.println(e);
}
finally {
System.out.println("finally block is always executed");
}
} }
Output: Inside try block
Exception handled

java.lang.ArithmeticException: / by zero

finally block is always executed


Built in Exception
Following is the list of Java Checked Exceptions Defined in java.lang.

Sr.No. Exception & Description

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.

Sr.No. Exception & Description


ArithmeticException
1
Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException
2
Array index is out-of-bounds.
ArrayStoreException
3
Assignment to an array element of an incompatible type.
ClassCastException
4
Invalid cast.
IllegalArgumentException
5
Illegal argument used to invoke a method.
IllegalMonitorStateException
6
Illegal monitor operation, such as waiting on an unlocked thread.
IllegalStateException
7
Environment or application is in incorrect state.
IllegalThreadStateException
8 Requested operation not compatible with the current thread
state.
IndexOutOfBoundsException
9
Some type of index is out-of-bounds.
NegativeArraySizeException
10
Array created with a negative size.
Built in Exception
following is the list of Java Unchecked Runtime Exception.
Sr.No. Exception & Description
NullPointerException
11
Invalid use of a null reference.
NumberFormatException
12
Invalid conversion of a string to a numeric format.
SecurityException
13
Attempt to violate security.
StringIndexOutOfBounds
14
Attempt to index outside the bounds of a string.
UnsupportedOperationException
15
An unsupported operation was encountered.
Built
Example:
in Exception
// Java program to demonstrate
// ArithmeticException
class ArithmeticException_Demo {
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a / b; // cannot divide by zero
System.out.println("Result = " + c);
}
catch (ArithmeticException e) {
System.out.println("Can't divide a number by 0");
}
}
}
Built in Exception
Example:
// Java program to demonstrate
// ArrayIndexOutOfBoundException
class ArrayIndexOutOfBound_Demo {
public static void main(String args[])
{
try {
int a[] = new int[5];
a[6] = 9; }
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index is Out Of Bounds");
}
}
}

User define Exception
Java exceptions cover almost all the general types of exceptions that may occur in the programming. However, we sometimes need to create custom exceptions.
 Following are a few of the reasons to use custom exceptions:
 To catch and provide specific treatment to a subset of existing Java exceptions.
 Business logic exceptions: These are the exceptions related to business logic and workflow. It is useful for the application users or the developers to understand the
exact problem.
 Example:
// A Class that represents use-defined exception
class MyException extends Exception {
}
// A Class that uses above MyException
public class setText {
// Driver Program
public static void main(String args[])
{
try {
// Throw an object of user defined exception
throw new MyException();
}
catch (MyException ex) {
System.out.println("Caught");
System.out.println(ex.getMessage());
}
}
}
Thank You!!!

You might also like