Exception Handling
in JAVA
Part-1
Instructor Name: Dr. Samia Ijaz
Department of Computer Science, HITEC University, Taxila, Pakistan
Outline
2
◻ What is an Exception
◻ Types of Exceptions
◻ What is an Error
◻ Error vs Exception
◻ What is an Exception Handling
◻ Why we use Exception Handling
What is an Exception?
3
• Dictionary Meaning: Exception is an abnormal condition.
• A Java exception is a runtime error that alters the normal flow of the program.
• It is an object that describes an exceptional (that is, error) condition in a piece
of code.
• When an exceptional condition arises, an object representing that exception is
created and thrown in the method that caused the error.
• That method may handle the exception itself, or pass it on.
What is an Exception?
4
• Java exception handling is managed via five keywords: try, catch, throw,
throws, and finally.
• Derived from class Exception, said to be “thrown” and an Exception handler
“catches” it.
• For instance, ClassNotFoundException, IOException, SQLException, etc.
What is an Exception?
5
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed after try block
ends
}
What is Exception?
6
Example Program – With no Exception Handler by the developer
7
class Calculator {
static int division(int a, int b) {
return a / b;
}
}
public class Main {
public static void main(String[] args) {
int result = [Link](10, 0);
[Link]("Result: " + result);
}
}
Example Program – With Exception Handler
8
class Calculator { public class ExceptionDemo {
public int divide(int a, int b) { public static void main(String[] args) {
return a / b; Calculator calculator = new Calculator();
} try {
} int result = [Link](10, 0);
[Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]("Error: Division by zero");
} finally {
[Link]("Program execution
completed.");
} } }
Example Program – With Exception Handler (modified version)
9
class Calculator { public class ExceptionDemo {
public static int divide(int a, int b) { public static void main(String[] args) {
return a / b; try {
} int result = [Link](10, 0);
} [Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]("Error: Division by zero");
} finally {
[Link]("Program execution
completed.");
}
}
}
Use of Throw keyword
10
◻So far, you have only been catching exceptions that are thrown by
the Java run-time system.
◻However, it is possible for your program to throw an exception
explicitly, using the throw statement.
Example – Using throw keyword
11
class Calculator { public class ExceptionDemo {
public static int divide(int a, int b) { public static void main(String[] args) {
try { int result1 = [Link](10, 2);
if (b == 0) { [Link]("Result1: " +
throw new ArithmeticException("Division by result1);
zero error");
} int result2 = [Link](20, 0);
return a / b; [Link]("Result2: " +
} catch (ArithmeticException e) { result2); // This will print an error
message
[Link]("Error: " + [Link]());
}
return Integer.MIN_VALUE; // or some default
value indicating error }
}}}
Types of Exceptions
12
Exceptions are divided into two categories:
• Checked Exceptions
• A type of exception in Java that the compiler requires you to handle explicitly in
your code.
• When a method throws a checked exception, the calling code must either catch and
handle the exception using a try-catch block or
• declare that it throws the exception using the throws keyword in its method
signature.
• Examples: IOException, FileNotFoundException, etc.
• Unchecked Exceptions
• Not chekced at compile time.
• Known to the compiler at runtime, also called runtime Exceptions.
• Examples: ArithmeticException, ArrayIndexOutOfBoundException, etc.
Unchecked Exception (Example-1)
13
class Calculator { public class ExceptionDemo {
public int divide(int a, int b) { public static void main(String[] args) {
return a / b; Calculator calculator = new Calculator();
} try {
} int result = [Link](10, 0);
[Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]("Error: Division by zero");
} finally {
[Link]("Program execution
completed.");
} } }
Unchecked Exception (Example-2)
14
// Java program illustrating exception thrown
// by AritmeticExcpetion class
public class ExceptionEg
{
public static void main(String[] args)
{ Output:
int a = 5, b = 0;
[Link]: / by zero
// Attempting to divide by zero at [Link]([Link])
try {
int c = a / b;
}
catch (ArithmeticException e)
{
[Link]();
} This method prints a stack trace for this object on the
} standard error output stream.
}
Unchecked Exception (printStackTrace())
15
◻printStackTrace() is a method available in the Throwable class
(which ArithmeticException class inherits from).
◻This method prints the stack trace of the exception, which includes
🞑 information about the sequence of method calls that led to the
exception being thrown.
🞑 It provides a detailed trace of what happened leading up to the
exception.
◻By calling [Link](), you're instructing Java to print this
detailed information about the exception to the console.
Checked Exception (Example : try-catch)
16
import [Link];
import [Link];
import [Link];
public class Main {
public static void main(String[] args) {
try {
File file = new File("[Link]");
FileReader fr = new FileReader(file); // This line may throw
FileNotFoundException
} catch (FileNotFoundException e) {
[Link]("File not found: " + [Link]());
}
}
}
Terms used in Exception Handling
17
• Throws: If a method is capable of causing an exception that it does not handle,
it must specify this behavior so that callers of the method can guard themselves
against that exception.
• You do this by including a throws clause in the method’s declaration. Basically it is
used for IO Exception. A throws clause lists the types of exceptions that a method
might throw.
• This is necessary for all exceptions, except those of type Error or Runtime
Exception, or any of their subclasses. All other exceptions that a method can
throw must be declared in the throws clause. If they are not , a compile-time error
will result.
Checked Exception (Example – throws)
18
import [Link];
import [Link];
import [Link];
public class Main {
public static void main(String[] args) throws FileNotFoundException {
try {
File file = new File("[Link]");
FileReader fr = new FileReader(file); // This line may throw FileNotFoundException
} catch (FileNotFoundException e) {
[Link]("File not found: " + [Link]());
}
}
}
Checked Exception (Modified Example - throws)
19
import [Link]; public class Main {
import [Link]; public static void main(String[] args) {
import [Link]; try {
[Link]();
public class FileReaderUtil {
} catch (FileNotFoundException e) {
public static void readFile() throws
FileNotFoundException { [Link]("File not
found: " + [Link]());
File file = new File("[Link]");
FileReader fr = new FileReader(file); // }
This line may throw FileNotFoundException }
} }
}
Checked Exception (Example)
20
import [Link].*; while(( k = [Link]() ) != -1)
class Example {
{ [Link]((char)k);
public static void main(String args[]) }
{ /*The method close() closes
FileInputStream fis = null; the file input stream * It
/*This constructor FileInputStream(File filename) throws IOException*/
throws FileNotFoundException which is a
checked exception */ [Link]();
fis = new FileInputStream("B:/[Link]"); }
int k; }
Output:
/* Method read() of FileInputStream class Exception in thread "main" [Link]: Unresolved compilation
problems: Unhandled exception type FileNotFoundException
also throws a checked exception: IOException */ Unhandled exception type IOException
Unhandled exception type IOException
Finally Block
21
• The finally keyword is used in association with a try-catch block
and guarantees that a section of code will be executed, even if
an exception is thrown.
• The finally block will be executed after the try and catch blocks,
but before control transfers back to its origin.
• finally block will execute whether an exception occurs or not or
whether corresponding catch block found or not.
finally Block - Example
22
public class ExceptionDemo { • public static int divide(int a, int b)
public static void main(String[] {
args) { • try {
try { • return a / b;
int result = divide(10, 0); • } catch (ArithmeticException
[Link]("Result: " + e) {
result); • [Link]("Error:
} catch (ArithmeticException e) { Division by zero");
[Link]("Error: • return Integer.MIN_VALUE;
Division by zero"); • }
} finally { • }
[Link]("Finally
block executed."); } }
What is an Error?
23
• An Error “indicates serious problems that a reasonable application
should not try to catch.”
• Errors are the conditions which cannot get recovered by any handling
techniques.
• Errors belong to unchecked type and mostly occur at runtime.
• Examples: Out of memory error, a System crash error, hardware error,
StackOverflowError etc.
Error (Example)
24
// Java program illustrating stack overflow error
public class ErrorEg
// by doing infinite recursion
{
class StackOverflow
public static void main(String[] args)
{
{
public static void test(int i)
{
// eg of StackOverflowError
// No correct as base condition leads to
[Link](5);
// non-stop recursion.
}
if (i == 0)
}
return;
else Output:
{ Exception in thread "main" [Link]
at [Link]([Link])
test(i++); at [Link]([Link])
} at [Link]([Link])
} at [Link]([Link])
} at [Link]([Link])
...
Error vs Exception
25
Error Exception
1. An error represents a condition 1. An error which reasonable
serious enough that most applications should catch.
reasonable applications should 2. Array index out of bounds
not try to catch. 3. Arithmetic errors (divide by
2. Virtual Machine Error zero
3. Out of memory 4. Null Pointer Exception
4. Stack overflow 5. I/O Exceptions
5. Thread Death
6. Linkage Error
Error vs Exception and their Class Hierarchy
26
• [Link]
All Java errors implement the [Link], or
• [Link]
are extended from another inherited class therein. The
• [Link]
full hierarchy of error is:
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
The Java Virtual Machine is broken or has run out
of resources necessary for it to continue operating.
•[Link]
• [Link]
• [Link]
• [Link] The AssertionError in Java is thrown when an assert
statement fails (i.e. the result is false).
What is an Exception Handling?
27
• Exception handling is a framework that is used to handle runtime
errors only, compile time errors are not handled by exception
handling in java.
• Exception handling is one of the most important feature of java
programming that allows us to handle the runtime errors caused
by exceptions.
Why we use Exception Handling?
28
To maintain the normal flow of the application.
An exception normally disrupts the normal flow of the
application that is why we use exception handling.
How we can handle the Exceptions?
Multi-Catch Block
29
public class TestMultipleCatchBlock
{ public static void main(String args[])
{
try At a time only one
Exception is occurred
{ and at a time only one
int a[]=new int[5]; catch block is
a[5]=30; executed.
a[5]=30/0;
} All catch blocks must be
catch (ArithmeticException e) ordered from most
specific to most general
{[Link]("task1 is i.e. catch for
completed");} ArithmeticException must
catch (ArrayIndexOutOfBoundsException e) come before catch for
{[Link]("task 2 completed");} Exception .
catch (Exception e)
{[Link]("common task completed");}
[Link]("rest of the code...");
Multi-Catch Block
30
public class Exception_handler { catch (NumberFormatException e) {
public static void main(String[] args) { [Link]("Number format
try { exception: " + [Link]());
// Divide by zero exception }catch (ArithmeticException e) {
int result = 10 / 2; [Link]("Divide by zero
error: " + [Link]());
// Array index out of bounds exception
} catch
int[] numbers = {1, 2, 3};
(ArrayIndexOutOfBoundsException e) {
[Link](numbers[5]);
[Link]("Array index out of
// Integer variable assigned a string value bounds: " + [Link]());
exception
} catch (Exception e) {
String str = "Hello";
[Link]("Generic exception:
int number = [Link](str); " + [Link]());
}
User-defined Exception (Example)
/* This is my Exception class, I have named it class Example1
MyException * you can give any name, just {
public static void main(String args[])
remember that it should * extend Exception class */
{
try
class MyException extends Exception { [Link]("Starting of try block");
{ // I'm throwing the custom exception using throw
String str1; throw new MyException("This is My error Message");
/* Constructor of custom exception class * here I am }
copying the message that we are passing while * catch(MyException exp)
{
throwing the exception to a string and then
[Link]("Catch Block") ; [Link](exp) ;
displaying * that string along with the message. */ }
}
MyException(String str2) }
{ str1=str2; }
public String toString()
{ return ("MyException Occurred: "+str1) ; }
} Output:
Starting of try block
Catch Block
MyException Occurred: This is My
error Message
32
Thanks