SlideShare a Scribd company logo
JAVA Programming Unit-IV
MODULE - A
Exception Handling
 Benefits of Exception handling
 The classification of exceptions-
 Exception Hierarchy
 Checked Exceptions
 UnChecked Exceptions
 Usage of try, catch, throw, throws and finally.
 Creating Own Exception Subclasses
Department of CSE
Java Programming Unit 4
MALLA REDDY UNIVERSITY
Benefits of Exception Handling
• Error Detection and Debugging: Exception handling helps detect errors and
exceptions that occur during program execution, making it easier to identify and
debug issues.
• Program Robustness: By handling exceptions gracefully, you can prevent your
program from crashing or terminating abruptly due to unexpected conditions,
improving its robustness.
• Separation of Error-Handling Logic: Exception handling allows you to
separate error-handling logic from the main program flow, making your code
more organized and maintainable.
• Maintainability: Using exception handling makes your code more maintainable
and readable by clearly delineating error-handling code from regular program
logic.
• Enhanced User Experience: Properly handled exceptions contribute to a more
user-friendly experience by presenting meaningful error messages.
Department of CSE
Java Programming Unit 4
MALLA REDDY UNIVERSITY
Exception handling
An exception is a problem that arises during the execution of a program. When
an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended,
therefore these exceptions are to be handled.
What is Exception in Java?
In Java, an exception is an event that disrupts the normal flow of the program.
It is an object which is thrown at runtime.
What is Exception Handling?
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, etc.
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
Common Scenarios of Java Exceptions
1) A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
int a = 50/0; // ArithmeticException
2) A scenario where NullPointerException occurs
If we have a null value in any variable, performing any operation on the variable
throws a NullPointerException.
String s = null;
System.out.println(s.length()); // NullPointerException
3) A scenario where NumberFormatException occurs
If the formatting of any variable or number is mismatched, it may result
into NumberFormatException. Suppose we have a string variable that has
characters; converting this variable into digit will cause NumberFormatException. So,
String s = "abc";
int i = Integer.parseInt(s); // NumberFormatException
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
4) A scenario where ArrayIndexOutOfBoundsException occurs
When an array exceeds to it's size, ArrayIndexOutOfBoundsException
occurs.
There may be other reasons to occur ArrayIndexOutOfBoundsException.
Consider the following statements.
int a[ ] = new int[5];
a[10] = 50; // ArrayIndexOutOfBoundsException
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked.
An error is considered as the unchecked exception. However, according to ORACLE, there are
three types of exceptions namely:
1. Checked Exception 2. Unchecked Exception and 3.Error.
Difference between Checked and Unchecked Exceptions:
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error are
known as checked exceptions. For example, IOException, SQLException, etc.
Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For
example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException,
etc.
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
3) Error: Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError.
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
Checked Exception in java
• The code below shows the FileInputStream method from the java.io package.
• This method throws a checked exception and the compiler is forcing us to handle it.
MALLA REDDY UNIVERSITY
import java.io.File;
import java.io.FileInputStream;
public class CheckedException {
public void readFile() {
String fileName = "file does not exist";
File file = new File(fileName);
FileInputStream stream = new FileInputStream(file);
} }
Department of CSE
Java Programming Unit 4
Unchecked Exception
• It occurs at the time of execution is known as run time exception.
• It reflects some error inside the program logic.
Common examples of unchecked exceptions in Java include:
• NullPointerException: Thrown when an attempt is made to access a null object reference.
• ArrayIndexOutOfBoundsException: Thrown when trying to access an array element with an invalid index.
• ArithmeticException: Thrown when an arithmetic operation results in an error, such as division by zero.
package mypack;
public class DivisionByZero{
public static void main(String... args) {
int a = 50, b = 0;
int c = divideAndSquare(a, b);
System.out.println(c);
}
static int divideAndSquare(int x, int y){
int z = x / y;
return z * z;}}
OutPut: Error: Could not find or load main
class DivisionByZero
Caused by: java.lang.NoClassDefFoundError:
mypack/DivisionByZero (wrong name:
DivisionByZero)
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
ArrayIndexOutOfBoundsException
• ArrayIndexOutOfBoundsException is an unchecked exception in Java that occurs
when an attempt is made to access an array element at an invalid index.
• The index can be either negative or greater than or equal to the size of the array.
• For example, if an array has 5 elements, trying to access the 6th element will result in
an ArrayIndexOutOfBoundsException.
class Main{
public static void main(String args[]) {
int arr[] = new int[4];
arr[0] = 1;
System.out.println(arr[0]);
System.out.println("ParseException
occurred: " +arr[5]);} }
Output: 1
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException
: Index 5 out of bounds for length 4
at Main.main(Main.java:17)
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
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:
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
Hierarchy of Java Exception classes
The class at the top of the exception class hierarchy is the Throwable
class, which is a direct subclass of the Object class.
Throwable has two direct subclasses - Exception and Error.
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
Exception: Most of the cases exceptions are caused by our program and these are recoverable.
Error: Most of the cases errors are not caused by our program these are due to lack of system resources and these are
non-recoverable.
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
Types of Exception: 1). Checked Exceptions.
2). Unchecked Exception.
1). Checked Exception: Checked exceptions are called
compile-time exceptions because these exceptions are
checked at compile-time by the compiler.
2). Unchecked Exceptions: The unchecked exceptions are
just opposite to the checked exceptions. The compiler will
not check these exceptions at compile time.
1). Checked Exception
What is a Checked Exception?
A checked exception is the one that the compiler checks or notifies during compilation.
Checked Exceptions are also known as compile-time exceptions.
These exceptions cannot be ignored.
If a code within a function throws a checked exception,
the function must handle the exception or specify it using the throws keyword.
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
Example:-1
A FileReader class is used in a file handling programme to read data from a file.
If the file specified in its constructor does not exist, a FileNotFoundException occurs,
and the compiler prompts the programmer to handle the exception.
Here, If the Name.txt file is not present in the specified location during the compilation, this
code will throw an error.
import java.io.File;
import java.io.FileReader;
public class Test{
public static void main(String args[ ]) {
File file = new File("E://Name.txt");
FileReader fr = new FileReader(file);
}
}
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type FileNotFoundException
Using try Catch: Ex-2
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
public class Test {
public static void main(String args[ ]) {
try {
File file = new File("C:Name.txt");
FileReader fr = new FileReader(file);
// Now you can use the FileReader object 'fr' to read from the file
} catch (FileNotFoundException e) { // Handle the case where the file is not found
e.printStackTrace( ); // or handle it in some other way
}
}
}
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
What is an Unchecked Exception?
An unchecked exception occurs during the execution process. Unchecked Exceptions are also
known as runtime exceptions. Programming mistakes, such as logic errors or improper use of
an API, are examples of this. Runtime exceptions are ignored during compilation.
Example: If a 7-element array is declared and the programme attempts to access its 8th
element, an ArrayIndexOutOfBoundsExceptionexception occurs. Here, the below program
will be successfully compiled, but it’ll throw an exception at runtime.
public class Test{
public static void main(String args[ ]) {
int num[ ] = {100, 20, 30, 40, 50, 60, 70};
System.out.println(num[7]);
}
}
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
2). Unchecked Exception
Output:
Exception in thread "main" java. Lang.ArrayIndexOutOfBoundsException: Index 8 out of bounds for length 7
at Test.main(Test.java:7)
Error: MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
Error:-An error is an unwanted problem in the program.
• Syntax Error:- prevents code from executing
• Runtime Error :- generates an error when the program is executing
• logical Error:- does not generate an error message due to a fault in the codes logic.
• Syntax Errors(Compile time errors):- syntax is a set of rules that specifies a structured
combination of words and symbols.
Ex:- Misspelled class, variable or method names
mispelled keywords
Missing semicolons
Missing return type for Methods
public class SyntaxError {
public static void main(String[ ] args) {
int x, y, total;
x = 10;
y = 6;
Total = x + y;
System.out.println("total is"+total);
}
}
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
Runtime error: Runtime errors detected when a program executes
public class RuntimeError {
public static void main(String[ ] args) {
int a, b, x, y, result, sum;
a = x = 10;
b = y = 0;
sum = x+y;
result = a/b;
System.out.println("what is 10/0"+result);
System.out.println("what is 10+0"+sum);
}
}
SyntaxError Runtime error
Java try-catch block
Java try block
• Java try block is used to enclose the code that might throw an exception. It must be used
within the method.
• If an exception occurs at the particular statement in the try block, the rest of the block code
will not execute.
• So, it is recommended not to keep the code in try block that will not throw an exception.
• Java try block must be followed by either catch or finally block.
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
Syntax of Java try-catch:
try { //code that may throw an exception
} catch(Exception_class_Name ref) {
}
Syntax of try-finally block:
try{ //code that may throw an exception
} finally {
}
Java catch block
• Java catch block is used to handle the Exception by declaring the type of exception
within the parameter. The declared exception must be the parent class exception ( i.e.,
Exception) or the generated exception type.
• However, the good approach is to declare the generated type of exception. The catch
block must be used after the try block only. You can use multiple catch block with a
single try block.
Internal Working of Java try-catch block:
The JVM firstly checks whether the exception is handled or not.
If exception is not handled, JVM provides a default exception
handler that performs the following tasks:
• Prints out exception description.
• Prints the stack trace (Hierarchy of methods where the
exception occurred).
• Causes the program to terminate.
But if the application programmer handles the exception, the normal
flow of the application is maintained, i.e., rest of the code is executed.
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
Problem without exception handling
public class TryCatchExample1 {
public static void main(String[ ] args) {
int data=50/0; //may throw exception
System.out.println("rest of the code");
} }
Exception in thread "main" java.lang.ArithmeticException: / by zero
Solution by exception handling:
public class JavaExceptionExample{
public static void main(String args[ ]){
System.out.println("Execution start...");
try{ //code that may raise exception
int data = 100/0;
} catch (ArithmeticException e) {
System.out.println(e);
} //rest code of the program
System.out.println("rest of the code...");
}
}
OUTPUT:
Execution start...
Exception in thread main java.lang.
ArithmeticException: / by zero
rest of the code...
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
Handling the exception using the parent class exception.
public class TryCatchExample4 {
public static void main(String[ ] args) {
System.out.println("Execution start...");
try {
int data = 50/0; //may throw
exception } // handling the exception by
using
Exception class
catch(Exception e) {
System.out.println(e);}
System.out.println("rest of the code");
} }
Execution start...
java.lang.ArithmeticException: / by zero
rest of the code
Example to print a custom message on exception.
public class TryCatchExample5 {
public static void main(String[] args) {
System.out.println(“Execution Starts...”);
try{
int data=50/0; //may throw exception}
// handling the exception
catch(Exception e) {
// displaying the custom message
System.out.println("Can't divided by zero");}
} }
Execution Starts...
Can't divided by zero
Department of CSE
Java Programming Unit 4
Example to resolve the exception in a catch block.
public class TryCatchExample6 {
public static void main(String[ ] args) {
int i=50;
int j=0;
int data;
try{
data=i/j; //may throw exception}
// handling the exception
catch(Exception e){
// resolving the exception in catch block
System.out.println(i/(j+2)); }
} }
handling the generated exception (Arithmetic
Exception) with a different type of exception class
ArrayIndexOutOfBoundsException).
public class TryCatchExample8 {
public static void main(String[] args) {
try {
int data=50/0; //may throw exception}
// try to handle the ArithmeticException using
ArrayIndexOutOfBoundsException
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
} }
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
Java Catch Multiple Exceptions-Java Multi-catch block
A try block can be followed by one or more catch blocks. Each catch
block must contain a different exception handler. So, if you have to
perform different tasks at the occurrence of different exceptions, use
java multi-catch block.
Points to remember:
• At a time only one exception occurs and at a time only one catch
block is executed.
• All catch blocks must be ordered from most specific to most general,
i.e. catch for ArithmeticException must come before catch for
Exception.
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
Flowchart of Multi-catch Block MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
MultipleCatchBlock1
public class MultipleCatchBlock1 {
public static void main(String[] args) {
try{
int a[ ] = new int[5];
a[5] = 30/0;
} catch(ArithmeticException e){
System.out.println("Arithmetic Exception occurs");
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBounds Exception occurs");
} catch(Exception e) {
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
} Arithmetic Exception occurs
rest of the code
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
MultipleCatchBlock
public class MultipleCatchBlock2 {
public static void main(String[ ] args) {
try{
int a[ ] = new int[5];
System.out.println(a[10]);
} catch(ArithmeticException e) {
System.out.println("Arithmetic Exception occurs");
} catch(ArrayIndexOutOfBoundsException e){
System.out.println("ArrayIndexOutOfBounds Exception occurs");
} catch(Exception e) {
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
} ArrayIndexOutOfBounds Exception occurs
rest of the code
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
Example to handle the exception without maintaining the order of exceptions (i.e. from
most specific to most general).
class MultipleCatchBlock5{
public static void main(String args[]){
try{
int a[ ] = new int[5];
a[5] = 30/0;
} catch(Exception e){
System.out.println("common task completed");
} catch(ArithmeticException e){
System.out.println("task1 is completed");
} catch(ArrayIndexOutOfBoundsException e){
System.out.println("task 2 completed");
}
System.out.println("rest of the code...");
}
}
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
Java Nested try block
• In Java, using a try block inside another try
block is permitted. It is called as nested try
block. Every statement that we enter a
statement in try block, context of that
exception is pushed onto the stack.
• For example, the inner try block can be used
to handle ArrayIndexOutOfBoundsException
while the outer try block can handle the
ArithemeticException (division by zero).
Why use nested try block
• Sometimes a situation may arise where a part
of a block may cause one error and the entire
block itself may cause another error. In such
cases, exception handlers have to be nested.
Example:
public class NestedTryBlock{
public static void main(String args[ ]){
//outer try block
try{
try{//inner try block 1
System.out.println("going to divide by 0");
int b = 39/0;
} //catch block of inner try block 1
catch(ArithmeticException e) {
System.out.println(e);
}
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
//inner try block 2
try{
int a[ ] = new int[5];
//assigning the value out of array bounds
a[5] = 4;
} //catch block of inner try block 2
catch(ArrayIndexOutOfBoundsException e) {
System.out.println(e); }
System.out.println("other statement"); }
//catch block of outer try block
catch(Exception e) {
System.out.println("handled the exception
(outer catch)");
}
System.out.println("normal flow..");
}
}
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
Java finally block
• 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.
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
public class TestFinallyBlock1{
public static void main(String args[]){
try {
System.out.println("Inside the try block"); //below code throws divide by zero exception
int data = 25/0;
System.out.println(data);
} //cannot handle Arithmetic type exception - can only accept Null Pointer type exception
catch(NullPointerException e){
System.out.println(e);
} //executes regardless of exception occured or not
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
Java throw Exception
In Java, exceptions allows us to write good quality codes where the errors are checked at the
compile time instead of runtime and we can create custom exceptions making the code
recovery and debugging easier.
Java throw keyword
• The Java throw keyword is used to throw an exception explicitly.
• We specify the exception object which is to be thrown. The Exception has some message
with it that provides the error description. These exceptions may be related to user inputs,
server, etc.
• We can throw either checked or unchecked exceptions in Java by throw keyword. It is
mainly used to throw a custom exception.
• We can also define our own set of conditions and throw an exception explicitly using
throw keyword. For example, we can throw ArithmeticException if we divide a number by
another number. Here, we just need to set the condition and throw exception using throw
keyword.
throw new exception_class("error message"); throw new IOException("sorry device
error");
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
public class TestThrow1 {
//function to check if person is eligible to vote or not
public static void validate(int age) {
if(age<18) { //throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote"); }
else {
System.out.println("Person is eligible to vote!!");
}
} //main method
public static void main(String args[ ]){ //calling the function validate(13);
System.out.println("rest of the code...");
}
}
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
import java.io.*;
public class TestThrow2 { //function to open a file
public static void method() throws FileNotFoundException
{ FileReader file = new FileReader("C:UsersAnuratiDesktopabc.txt");
BufferedReader fileInput = new BufferedReader(file);
throw new FileNotFoundException( );
} public static void main(String args[ ]) {//main method
try { method( );
} catch (FileNotFoundException e)
{ e.printStackTrace();
}
System.out.println("rest of the code...");
}
• If we throw a checked exception using throw keyword, it is must to
handle the exception using catch block or the method must declare it using throws declaration.
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
User-Defined Exceptions
Sometimes, the built-in exceptions in Java are not able to describe a certain
situation. In such cases, the user can also create exceptions which are called ‘user-
defined Exceptions’.
1) Create the New Exception Class extending Exception Class.
2) Create a Public Constructor for a New Class with String Type of Parameter.
3) Pass the string parameter to the Super Class.
4) Declare the Exception at the Method Level.
5) Create try block inside that Create a New Exception and throw it based
on some condition.
6) Write a catch block and use some Predefined Exceptions.
7) Write the Optionally finally block.
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
import java.util.Scanner;
class ExceptionDemo extends Exception{
public ExceptionDemo(String str) {
super(str); }
public static void main(String args[ ]) throws ExceptionDemo {
try {
Scanner sc = new Scanner(System.in) ;
System.out.println("Enter your Age : ");
int age = sc.nextInt( );
i f(age<18) {
throw new ExceptionDemo("You are not eligible for vote");
}
else {
System.out.println("You are eligible for vote");}
} catch(ExceptionDemo ed) {
ed.printStackTrace(); }
} }
C:UsersMRUHDesktopjavaex>java ExceptionDemo
Enter your Age : 17
ExceptionDemo: You are not eligible for vote
at ExceptionDemo.main(ExceptionDemo.java:15)
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
Java Exception Propagation
• An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the
previous method.
• If not caught there, the exception again drops down to the previous method, and so on until they are caught or
until they reach the very bottom of the call stack. This is called exception propagation.
• By default Unchecked Exceptions are forwarded in calling chain (propagated).
class TestExceptionPropagation1{
void m( ){
int data = 50/0; }
void n( ){ m( ); }
void p( ) { try{ n( );
} catch(Exception e){System.out.println("Exception Handled");}
}
public static void main(String args[ ]){
TestExceptionPropagation1 obj = new TestExceptionPropagation1();
obj.p();
System.out.println("Normal Flow...");
} }
Exception Handled
Nnormal Fow...
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
By default, Checked Exceptions are not forwarded in calling chain (propagated).
class TestExceptionPropagation2{
void m( ){
throw new java.io.IOException("device error"); //checked exception }
void n(){ m(); }
void p(){ try{ n(); }
catch(Exception e){
System.out.println("exception handeled");
}
}
public static void main(String args[ ]){
TestExceptionPropagation2 obj = new TestExceptionPropagation2( );
obj.p();
System.out.println("normal flow");
}
}
TestExceptionPropagation2.java:3: error: unreported exception
IOException; must be caught or declared to be thrown
throw new java.io.IOException("device error");//checked exception ^
1 error
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
Java throws keyword
• The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception.
• So, it is better for the programmer to provide the exception handling code so that the
normal flow of the program can be maintained.
• Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers' fault that he is not
checking the code before it being used.
return_type method_name() throws exception_class_name{
//method code
}
Which exception should be declared?
Ans: Checked exception only, because:
Unchecked exception: under our control so we can correct our code.
error: beyond our control.
For example, we are unable to do anything if there occurs VirtualMachineError
or StackOverflowError.
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error"); //checked exception
}
void n() throws IOException{ m(); }
void p(){ try{ n();
} catch(Exception e) {
System.out.println("exception handled");}
}
public static void main(String args[ ]){
Testthrows1 obj = new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
} exception handled
normal flow...
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
• If we are calling a method that declares an exception, we must either caught or declare the exception.
There are two cases:
• Case 1: We have caught the exception i.e. we have handled the exception using try/catch block.
• Case 2: We have declared the exception i.e. specified throws keyword with the method.
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
Case 1: Handle Exception Using try-catch block
• In case we handle the exception, the code will be executed fine whether exception occurs
during the program or not.
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error"); }
}
public class Testthrows2{
public static void main(String args[ ]){
try{ M m = new M();
m.method();
} catch(Exception e){
System.out.println(“Exception Handled");
}
System.out.println(“Normal Flow...");
} }
Exception Handled
Normal Flow...
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
Case 2: Declare Exception
In case we declare the exception, if exception does not occur, the code will be executed fine.
In case we declare the exception and the exception occurs, it will be thrown at runtime because
throws does not handle the exception.
import java.io.*;
class M {
void method( ) throws IOException {
System.out.println("device operation performed");
} }
class Testthrows3 {
public static void main(String args[ ]) throws IOException { //declare exception
M m = new M();
m.method();
System.out.println("normal flow...");
} }
device operation performed
normal flow...
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
import java.io.*;
class M{
void method( ) throws IOException{
throw new IOException("device error");
}
}
class Testthrows4{
public static void main(String args[ ]) throws IOException{ //declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
}
}
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4
Difference between throw and throws in Java
Name throw throws
Definition Java throw keyword is used throw an
exception explicitly in the code, inside the
function or the block of code.
Java throws keyword is used in the method
signature to declare an exception which might be
thrown by the function while the execution of the
code.
checked /
unchecked
Type of exception Using throw keyword,
we can only propagate unchecked
exception i.e., the checked exception
cannot be propagated using throw only.
Using throws keyword, we can declare both
checked and unchecked exceptions. However,
the throws keyword can be used to propagate
checked exceptions only.
Syntax The throw keyword is followed by an
instance of Exception to be thrown.
The throws keyword is followed by class names
of Exceptions to be thrown.
Declaration throw is used within the method. throws is used with the method signature.
Internal
implementati
on
We are allowed to throw only one
exception at a time i.e. we cannot throw
multiple exceptions.
We can declare multiple exceptions using throws
keyword that can be thrown by the method. For
example, main() throws IOException,
SQLException.
MALLA REDDY UNIVERSITY
Department of CSE
Java Programming Unit 4

More Related Content

PPT
Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
PPT
Exception Handling in java masters of computer application
PPTX
L14 exception handling
PPTX
exception handling in java
PPTX
Lec-01 Exception Handling in Java_javatpoint.pptx
PPTX
Event handling
PDF
Exception handling
PPT
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
Exception Handling in java masters of computer application
L14 exception handling
exception handling in java
Lec-01 Exception Handling in Java_javatpoint.pptx
Event handling
Exception handling
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming

Similar to Java_Prog_-_UNIT-IV_Part_A_Modinnfy.pptx (20)

PPTX
OBJECT ORIENTED PROGRAMMING_Unit3_NOTES first half.pptx
DOCX
What is an exception in java?
PPTX
Z blue exception
PPTX
Exceptions in java
DOCX
MODULE5_EXCEPTION HANDLING.docx
PDF
Chapter 5 Exception Handling (1).pdf
PPTX
Exception Handling.pptx
PPTX
Exception handling in java
PDF
Java_Exception-CheatSheet_Edureka.pdf
PPT
Itp 120 Chapt 18 2009 Exceptions & Assertions
PPSX
Java Exceptions
PPSX
Java Exceptions Handling
PDF
Class notes(week 8) on exception handling
PPTX
Java Exception Handling
PPTX
1.12 Exception Handing.pptx
DOCX
VTU MCA 2022 JAVA Exceeption Handling.docx
PPT
Java Exception Handling & IO-Unit-3 (1).ppt
PPTX
Exception handling and throw and throws keyword in java.pptx
PPTX
using Java Exception Handling in Java.pptx
PPTX
Interface andexceptions
OBJECT ORIENTED PROGRAMMING_Unit3_NOTES first half.pptx
What is an exception in java?
Z blue exception
Exceptions in java
MODULE5_EXCEPTION HANDLING.docx
Chapter 5 Exception Handling (1).pdf
Exception Handling.pptx
Exception handling in java
Java_Exception-CheatSheet_Edureka.pdf
Itp 120 Chapt 18 2009 Exceptions & Assertions
Java Exceptions
Java Exceptions Handling
Class notes(week 8) on exception handling
Java Exception Handling
1.12 Exception Handing.pptx
VTU MCA 2022 JAVA Exceeption Handling.docx
Java Exception Handling & IO-Unit-3 (1).ppt
Exception handling and throw and throws keyword in java.pptx
using Java Exception Handling in Java.pptx
Interface andexceptions
Ad

Recently uploaded (20)

PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PPTX
web development for engineering and engineering
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PDF
Well-logging-methods_new................
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
DOCX
573137875-Attendance-Management-System-original
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PPT
Project quality management in manufacturing
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PPT
Mechanical Engineering MATERIALS Selection
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PDF
PPT on Performance Review to get promotions
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PPTX
Sustainable Sites - Green Building Construction
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
web development for engineering and engineering
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
Well-logging-methods_new................
CYBER-CRIMES AND SECURITY A guide to understanding
573137875-Attendance-Management-System-original
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
Project quality management in manufacturing
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
Mechanical Engineering MATERIALS Selection
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PPT on Performance Review to get promotions
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
Foundation to blockchain - A guide to Blockchain Tech
Sustainable Sites - Green Building Construction
Ad

Java_Prog_-_UNIT-IV_Part_A_Modinnfy.pptx

  • 1. JAVA Programming Unit-IV MODULE - A Exception Handling  Benefits of Exception handling  The classification of exceptions-  Exception Hierarchy  Checked Exceptions  UnChecked Exceptions  Usage of try, catch, throw, throws and finally.  Creating Own Exception Subclasses Department of CSE Java Programming Unit 4 MALLA REDDY UNIVERSITY
  • 2. Benefits of Exception Handling • Error Detection and Debugging: Exception handling helps detect errors and exceptions that occur during program execution, making it easier to identify and debug issues. • Program Robustness: By handling exceptions gracefully, you can prevent your program from crashing or terminating abruptly due to unexpected conditions, improving its robustness. • Separation of Error-Handling Logic: Exception handling allows you to separate error-handling logic from the main program flow, making your code more organized and maintainable. • Maintainability: Using exception handling makes your code more maintainable and readable by clearly delineating error-handling code from regular program logic. • Enhanced User Experience: Properly handled exceptions contribute to a more user-friendly experience by presenting meaningful error messages. Department of CSE Java Programming Unit 4 MALLA REDDY UNIVERSITY
  • 3. Exception handling An exception is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore these exceptions are to be handled. What is Exception in Java? In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime. What is Exception Handling? Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, etc. MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 4. Common Scenarios of Java Exceptions 1) A scenario where ArithmeticException occurs If we divide any number by zero, there occurs an ArithmeticException. int a = 50/0; // ArithmeticException 2) A scenario where NullPointerException occurs If we have a null value in any variable, performing any operation on the variable throws a NullPointerException. String s = null; System.out.println(s.length()); // NullPointerException 3) A scenario where NumberFormatException occurs If the formatting of any variable or number is mismatched, it may result into NumberFormatException. Suppose we have a string variable that has characters; converting this variable into digit will cause NumberFormatException. So, String s = "abc"; int i = Integer.parseInt(s); // NumberFormatException MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 5. 4) A scenario where ArrayIndexOutOfBoundsException occurs When an array exceeds to it's size, ArrayIndexOutOfBoundsException occurs. There may be other reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements. int a[ ] = new int[5]; a[10] = 50; // ArrayIndexOutOfBoundsException MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 6. Types of Java Exceptions There are mainly two types of exceptions: checked and unchecked. An error is considered as the unchecked exception. However, according to ORACLE, there are three types of exceptions namely: 1. Checked Exception 2. Unchecked Exception and 3.Error. Difference between Checked and Unchecked Exceptions: 1) Checked Exception The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at compile-time. 2) Unchecked Exception The classes that inherit the RuntimeException are known as unchecked exceptions. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime. MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 7. 3) Error: Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError. MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 8. Checked Exception in java • The code below shows the FileInputStream method from the java.io package. • This method throws a checked exception and the compiler is forcing us to handle it. MALLA REDDY UNIVERSITY import java.io.File; import java.io.FileInputStream; public class CheckedException { public void readFile() { String fileName = "file does not exist"; File file = new File(fileName); FileInputStream stream = new FileInputStream(file); } } Department of CSE Java Programming Unit 4
  • 9. Unchecked Exception • It occurs at the time of execution is known as run time exception. • It reflects some error inside the program logic. Common examples of unchecked exceptions in Java include: • NullPointerException: Thrown when an attempt is made to access a null object reference. • ArrayIndexOutOfBoundsException: Thrown when trying to access an array element with an invalid index. • ArithmeticException: Thrown when an arithmetic operation results in an error, such as division by zero. package mypack; public class DivisionByZero{ public static void main(String... args) { int a = 50, b = 0; int c = divideAndSquare(a, b); System.out.println(c); } static int divideAndSquare(int x, int y){ int z = x / y; return z * z;}} OutPut: Error: Could not find or load main class DivisionByZero Caused by: java.lang.NoClassDefFoundError: mypack/DivisionByZero (wrong name: DivisionByZero) MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 10. ArrayIndexOutOfBoundsException • ArrayIndexOutOfBoundsException is an unchecked exception in Java that occurs when an attempt is made to access an array element at an invalid index. • The index can be either negative or greater than or equal to the size of the array. • For example, if an array has 5 elements, trying to access the 6th element will result in an ArrayIndexOutOfBoundsException. class Main{ public static void main(String args[]) { int arr[] = new int[4]; arr[0] = 1; System.out.println(arr[0]); System.out.println("ParseException occurred: " +arr[5]);} } Output: 1 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException : Index 5 out of bounds for length 4 at Main.main(Main.java:17) MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 11. 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: MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 12. Hierarchy of Java Exception classes The class at the top of the exception class hierarchy is the Throwable class, which is a direct subclass of the Object class. Throwable has two direct subclasses - Exception and Error. MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 13. Exception: Most of the cases exceptions are caused by our program and these are recoverable. Error: Most of the cases errors are not caused by our program these are due to lack of system resources and these are non-recoverable. MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4 Types of Exception: 1). Checked Exceptions. 2). Unchecked Exception. 1). Checked Exception: Checked exceptions are called compile-time exceptions because these exceptions are checked at compile-time by the compiler. 2). Unchecked Exceptions: The unchecked exceptions are just opposite to the checked exceptions. The compiler will not check these exceptions at compile time.
  • 14. 1). Checked Exception What is a Checked Exception? A checked exception is the one that the compiler checks or notifies during compilation. Checked Exceptions are also known as compile-time exceptions. These exceptions cannot be ignored. If a code within a function throws a checked exception, the function must handle the exception or specify it using the throws keyword. MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 15. Example:-1 A FileReader class is used in a file handling programme to read data from a file. If the file specified in its constructor does not exist, a FileNotFoundException occurs, and the compiler prompts the programmer to handle the exception. Here, If the Name.txt file is not present in the specified location during the compilation, this code will throw an error. import java.io.File; import java.io.FileReader; public class Test{ public static void main(String args[ ]) { File file = new File("E://Name.txt"); FileReader fr = new FileReader(file); } } MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4 Output: Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unhandled exception type FileNotFoundException
  • 16. Using try Catch: Ex-2 import java.io.File; import java.io.FileReader; import java.io.FileNotFoundException; public class Test { public static void main(String args[ ]) { try { File file = new File("C:Name.txt"); FileReader fr = new FileReader(file); // Now you can use the FileReader object 'fr' to read from the file } catch (FileNotFoundException e) { // Handle the case where the file is not found e.printStackTrace( ); // or handle it in some other way } } } MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 17. What is an Unchecked Exception? An unchecked exception occurs during the execution process. Unchecked Exceptions are also known as runtime exceptions. Programming mistakes, such as logic errors or improper use of an API, are examples of this. Runtime exceptions are ignored during compilation. Example: If a 7-element array is declared and the programme attempts to access its 8th element, an ArrayIndexOutOfBoundsExceptionexception occurs. Here, the below program will be successfully compiled, but it’ll throw an exception at runtime. public class Test{ public static void main(String args[ ]) { int num[ ] = {100, 20, 30, 40, 50, 60, 70}; System.out.println(num[7]); } } MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4 2). Unchecked Exception Output: Exception in thread "main" java. Lang.ArrayIndexOutOfBoundsException: Index 8 out of bounds for length 7 at Test.main(Test.java:7)
  • 18. Error: MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4 Error:-An error is an unwanted problem in the program. • Syntax Error:- prevents code from executing • Runtime Error :- generates an error when the program is executing • logical Error:- does not generate an error message due to a fault in the codes logic. • Syntax Errors(Compile time errors):- syntax is a set of rules that specifies a structured combination of words and symbols. Ex:- Misspelled class, variable or method names mispelled keywords Missing semicolons Missing return type for Methods
  • 19. public class SyntaxError { public static void main(String[ ] args) { int x, y, total; x = 10; y = 6; Total = x + y; System.out.println("total is"+total); } } MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4 Runtime error: Runtime errors detected when a program executes public class RuntimeError { public static void main(String[ ] args) { int a, b, x, y, result, sum; a = x = 10; b = y = 0; sum = x+y; result = a/b; System.out.println("what is 10/0"+result); System.out.println("what is 10+0"+sum); } } SyntaxError Runtime error
  • 20. Java try-catch block Java try block • Java try block is used to enclose the code that might throw an exception. It must be used within the method. • If an exception occurs at the particular statement in the try block, the rest of the block code will not execute. • So, it is recommended not to keep the code in try block that will not throw an exception. • Java try block must be followed by either catch or finally block. MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4 Syntax of Java try-catch: try { //code that may throw an exception } catch(Exception_class_Name ref) { } Syntax of try-finally block: try{ //code that may throw an exception } finally { }
  • 21. Java catch block • Java catch block is used to handle the Exception by declaring the type of exception within the parameter. The declared exception must be the parent class exception ( i.e., Exception) or the generated exception type. • However, the good approach is to declare the generated type of exception. The catch block must be used after the try block only. You can use multiple catch block with a single try block. Internal Working of Java try-catch block: The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM provides a default exception handler that performs the following tasks: • Prints out exception description. • Prints the stack trace (Hierarchy of methods where the exception occurred). • Causes the program to terminate. But if the application programmer handles the exception, the normal flow of the application is maintained, i.e., rest of the code is executed. MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 22. Problem without exception handling public class TryCatchExample1 { public static void main(String[ ] args) { int data=50/0; //may throw exception System.out.println("rest of the code"); } } Exception in thread "main" java.lang.ArithmeticException: / by zero Solution by exception handling: public class JavaExceptionExample{ public static void main(String args[ ]){ System.out.println("Execution start..."); try{ //code that may raise exception int data = 100/0; } catch (ArithmeticException e) { System.out.println(e); } //rest code of the program System.out.println("rest of the code..."); } } OUTPUT: Execution start... Exception in thread main java.lang. ArithmeticException: / by zero rest of the code... MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 23. Handling the exception using the parent class exception. public class TryCatchExample4 { public static void main(String[ ] args) { System.out.println("Execution start..."); try { int data = 50/0; //may throw exception } // handling the exception by using Exception class catch(Exception e) { System.out.println(e);} System.out.println("rest of the code"); } } Execution start... java.lang.ArithmeticException: / by zero rest of the code Example to print a custom message on exception. public class TryCatchExample5 { public static void main(String[] args) { System.out.println(“Execution Starts...”); try{ int data=50/0; //may throw exception} // handling the exception catch(Exception e) { // displaying the custom message System.out.println("Can't divided by zero");} } } Execution Starts... Can't divided by zero Department of CSE Java Programming Unit 4
  • 24. Example to resolve the exception in a catch block. public class TryCatchExample6 { public static void main(String[ ] args) { int i=50; int j=0; int data; try{ data=i/j; //may throw exception} // handling the exception catch(Exception e){ // resolving the exception in catch block System.out.println(i/(j+2)); } } } handling the generated exception (Arithmetic Exception) with a different type of exception class ArrayIndexOutOfBoundsException). public class TryCatchExample8 { public static void main(String[] args) { try { int data=50/0; //may throw exception} // try to handle the ArithmeticException using ArrayIndexOutOfBoundsException catch(ArrayIndexOutOfBoundsException e) { System.out.println(e); } System.out.println("rest of the code"); } } MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 25. Java Catch Multiple Exceptions-Java Multi-catch block A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler. So, if you have to perform different tasks at the occurrence of different exceptions, use java multi-catch block. Points to remember: • At a time only one exception occurs and at a time only one catch block is executed. • All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must come before catch for Exception. MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 26. Flowchart of Multi-catch Block MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 27. MultipleCatchBlock1 public class MultipleCatchBlock1 { public static void main(String[] args) { try{ int a[ ] = new int[5]; a[5] = 30/0; } catch(ArithmeticException e){ System.out.println("Arithmetic Exception occurs"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("ArrayIndexOutOfBounds Exception occurs"); } catch(Exception e) { System.out.println("Parent Exception occurs"); } System.out.println("rest of the code"); } } Arithmetic Exception occurs rest of the code MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 28. MultipleCatchBlock public class MultipleCatchBlock2 { public static void main(String[ ] args) { try{ int a[ ] = new int[5]; System.out.println(a[10]); } catch(ArithmeticException e) { System.out.println("Arithmetic Exception occurs"); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("ArrayIndexOutOfBounds Exception occurs"); } catch(Exception e) { System.out.println("Parent Exception occurs"); } System.out.println("rest of the code"); } } ArrayIndexOutOfBounds Exception occurs rest of the code MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 29. Example to handle the exception without maintaining the order of exceptions (i.e. from most specific to most general). class MultipleCatchBlock5{ public static void main(String args[]){ try{ int a[ ] = new int[5]; a[5] = 30/0; } catch(Exception e){ System.out.println("common task completed"); } catch(ArithmeticException e){ System.out.println("task1 is completed"); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("task 2 completed"); } System.out.println("rest of the code..."); } } MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 30. Java Nested try block • In Java, using a try block inside another try block is permitted. It is called as nested try block. Every statement that we enter a statement in try block, context of that exception is pushed onto the stack. • For example, the inner try block can be used to handle ArrayIndexOutOfBoundsException while the outer try block can handle the ArithemeticException (division by zero). Why use nested try block • Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested. Example: public class NestedTryBlock{ public static void main(String args[ ]){ //outer try block try{ try{//inner try block 1 System.out.println("going to divide by 0"); int b = 39/0; } //catch block of inner try block 1 catch(ArithmeticException e) { System.out.println(e); } MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 31. //inner try block 2 try{ int a[ ] = new int[5]; //assigning the value out of array bounds a[5] = 4; } //catch block of inner try block 2 catch(ArrayIndexOutOfBoundsException e) { System.out.println(e); } System.out.println("other statement"); } //catch block of outer try block catch(Exception e) { System.out.println("handled the exception (outer catch)"); } System.out.println("normal flow.."); } } MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 32. Java finally block • 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. MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 33. public class TestFinallyBlock1{ public static void main(String args[]){ try { System.out.println("Inside the try block"); //below code throws divide by zero exception int data = 25/0; System.out.println(data); } //cannot handle Arithmetic type exception - can only accept Null Pointer type exception catch(NullPointerException e){ System.out.println(e); } //executes regardless of exception occured or not finally { System.out.println("finally block is always executed"); } System.out.println("rest of the code..."); } } MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 34. Java throw Exception In Java, exceptions allows us to write good quality codes where the errors are checked at the compile time instead of runtime and we can create custom exceptions making the code recovery and debugging easier. Java throw keyword • The Java throw keyword is used to throw an exception explicitly. • We specify the exception object which is to be thrown. The Exception has some message with it that provides the error description. These exceptions may be related to user inputs, server, etc. • We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly used to throw a custom exception. • We can also define our own set of conditions and throw an exception explicitly using throw keyword. For example, we can throw ArithmeticException if we divide a number by another number. Here, we just need to set the condition and throw exception using throw keyword. throw new exception_class("error message"); throw new IOException("sorry device error"); MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 35. public class TestThrow1 { //function to check if person is eligible to vote or not public static void validate(int age) { if(age<18) { //throw Arithmetic exception if not eligible to vote throw new ArithmeticException("Person is not eligible to vote"); } else { System.out.println("Person is eligible to vote!!"); } } //main method public static void main(String args[ ]){ //calling the function validate(13); System.out.println("rest of the code..."); } } MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 36. import java.io.*; public class TestThrow2 { //function to open a file public static void method() throws FileNotFoundException { FileReader file = new FileReader("C:UsersAnuratiDesktopabc.txt"); BufferedReader fileInput = new BufferedReader(file); throw new FileNotFoundException( ); } public static void main(String args[ ]) {//main method try { method( ); } catch (FileNotFoundException e) { e.printStackTrace(); } System.out.println("rest of the code..."); } • If we throw a checked exception using throw keyword, it is must to handle the exception using catch block or the method must declare it using throws declaration. MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 37. User-Defined Exceptions Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases, the user can also create exceptions which are called ‘user- defined Exceptions’. 1) Create the New Exception Class extending Exception Class. 2) Create a Public Constructor for a New Class with String Type of Parameter. 3) Pass the string parameter to the Super Class. 4) Declare the Exception at the Method Level. 5) Create try block inside that Create a New Exception and throw it based on some condition. 6) Write a catch block and use some Predefined Exceptions. 7) Write the Optionally finally block. MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 38. import java.util.Scanner; class ExceptionDemo extends Exception{ public ExceptionDemo(String str) { super(str); } public static void main(String args[ ]) throws ExceptionDemo { try { Scanner sc = new Scanner(System.in) ; System.out.println("Enter your Age : "); int age = sc.nextInt( ); i f(age<18) { throw new ExceptionDemo("You are not eligible for vote"); } else { System.out.println("You are eligible for vote");} } catch(ExceptionDemo ed) { ed.printStackTrace(); } } } C:UsersMRUHDesktopjavaex>java ExceptionDemo Enter your Age : 17 ExceptionDemo: You are not eligible for vote at ExceptionDemo.main(ExceptionDemo.java:15) MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 39. Java Exception Propagation • An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method. • If not caught there, the exception again drops down to the previous method, and so on until they are caught or until they reach the very bottom of the call stack. This is called exception propagation. • By default Unchecked Exceptions are forwarded in calling chain (propagated). class TestExceptionPropagation1{ void m( ){ int data = 50/0; } void n( ){ m( ); } void p( ) { try{ n( ); } catch(Exception e){System.out.println("Exception Handled");} } public static void main(String args[ ]){ TestExceptionPropagation1 obj = new TestExceptionPropagation1(); obj.p(); System.out.println("Normal Flow..."); } } Exception Handled Nnormal Fow... MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 40. By default, Checked Exceptions are not forwarded in calling chain (propagated). class TestExceptionPropagation2{ void m( ){ throw new java.io.IOException("device error"); //checked exception } void n(){ m(); } void p(){ try{ n(); } catch(Exception e){ System.out.println("exception handeled"); } } public static void main(String args[ ]){ TestExceptionPropagation2 obj = new TestExceptionPropagation2( ); obj.p(); System.out.println("normal flow"); } } TestExceptionPropagation2.java:3: error: unreported exception IOException; must be caught or declared to be thrown throw new java.io.IOException("device error");//checked exception ^ 1 error MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 41. Java throws keyword • The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception. • So, it is better for the programmer to provide the exception handling code so that the normal flow of the program can be maintained. • Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as NullPointerException, it is programmers' fault that he is not checking the code before it being used. return_type method_name() throws exception_class_name{ //method code } Which exception should be declared? Ans: Checked exception only, because: Unchecked exception: under our control so we can correct our code. error: beyond our control. For example, we are unable to do anything if there occurs VirtualMachineError or StackOverflowError. MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 42. import java.io.IOException; class Testthrows1{ void m()throws IOException{ throw new IOException("device error"); //checked exception } void n() throws IOException{ m(); } void p(){ try{ n(); } catch(Exception e) { System.out.println("exception handled");} } public static void main(String args[ ]){ Testthrows1 obj = new Testthrows1(); obj.p(); System.out.println("normal flow..."); } } exception handled normal flow... MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 43. • If we are calling a method that declares an exception, we must either caught or declare the exception. There are two cases: • Case 1: We have caught the exception i.e. we have handled the exception using try/catch block. • Case 2: We have declared the exception i.e. specified throws keyword with the method. MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 44. Case 1: Handle Exception Using try-catch block • In case we handle the exception, the code will be executed fine whether exception occurs during the program or not. import java.io.*; class M{ void method()throws IOException{ throw new IOException("device error"); } } public class Testthrows2{ public static void main(String args[ ]){ try{ M m = new M(); m.method(); } catch(Exception e){ System.out.println(“Exception Handled"); } System.out.println(“Normal Flow..."); } } Exception Handled Normal Flow... MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 45. Case 2: Declare Exception In case we declare the exception, if exception does not occur, the code will be executed fine. In case we declare the exception and the exception occurs, it will be thrown at runtime because throws does not handle the exception. import java.io.*; class M { void method( ) throws IOException { System.out.println("device operation performed"); } } class Testthrows3 { public static void main(String args[ ]) throws IOException { //declare exception M m = new M(); m.method(); System.out.println("normal flow..."); } } device operation performed normal flow... MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 46. import java.io.*; class M{ void method( ) throws IOException{ throw new IOException("device error"); } } class Testthrows4{ public static void main(String args[ ]) throws IOException{ //declare exception M m=new M(); m.method(); System.out.println("normal flow..."); } } MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4
  • 47. Difference between throw and throws in Java Name throw throws Definition Java throw keyword is used throw an exception explicitly in the code, inside the function or the block of code. Java throws keyword is used in the method signature to declare an exception which might be thrown by the function while the execution of the code. checked / unchecked Type of exception Using throw keyword, we can only propagate unchecked exception i.e., the checked exception cannot be propagated using throw only. Using throws keyword, we can declare both checked and unchecked exceptions. However, the throws keyword can be used to propagate checked exceptions only. Syntax The throw keyword is followed by an instance of Exception to be thrown. The throws keyword is followed by class names of Exceptions to be thrown. Declaration throw is used within the method. throws is used with the method signature. Internal implementati on We are allowed to throw only one exception at a time i.e. we cannot throw multiple exceptions. We can declare multiple exceptions using throws keyword that can be thrown by the method. For example, main() throws IOException, SQLException. MALLA REDDY UNIVERSITY Department of CSE Java Programming Unit 4