OOP - Chapter 4-Exception Handling
OOP - Chapter 4-Exception Handling
By: Rashid W.
November 2023
Tepi, Ethiopia
OOP | Unit Four-4: Exception Handling
Error: An Error indicates a serious problem that a reasonable application should not try to
catch.
Exception: Exception indicates conditions that a reasonable application might try to catch.
Exception Hierarchy
All exception and error types are subclasses of the class Throwable, which is the base class of
the hierarchy. One branch is headed by Exception. This class is used for exceptional conditions
that user programs should catch. NullPointerException is an example of such an exception.
Another branch, Error is used by the Java run-time system(JVM) to indicate errors having to do
with the run-time environment itself(JRE). StackOverflowError is an example of such an error.
Types of Exceptions
Java defines several types of exceptions that relate to its various class libraries. Java also
allows users to define their own exceptions.
1. Built-in Exceptions
Checked Exception
Unchecked Exception
2. User-Defined Exceptions
3. Error
1 Built-in Exceptions
Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are
suitable to explain certain error situations.
Unchecked Exception: Unchecked exceptions are not checked at compile-time, but they are
checked at runtime. 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.
2. User-Defined Exceptions: 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‟.
There are given some scenarios where unchecked exceptions may occur. They are as follows:
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
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException occurs
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be
other reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements.
Default Exception Handling: Whenever inside a method, if an exception has occurred, the
method creates an Object known as an Exception Object and hands it off to the run-time
system(JVM). The exception object contains the name and description of the exception and the
current state of the program where the exception has occurred. Creating the Exception Object
and handling it in the run-time system is called throwing an Exception. There might be a list of
the methods that had been called to get to the method where an exception occurred. This
ordered list of methods is called Call Stack. Now the following procedure will happen.
The run-time system searches the call stack to find the method that contains a block of
code that can handle the occurred exception. The block of the code is called an Exception
handler.
The run-time system starts searching from the method in which the exception occurred and
proceeds through the call stack in the reverse order in which methods were called.
If it finds an appropriate handler, then it passes the occurred exception to it. An
appropriate handler means the type of exception object thrown matches the type of
exception object it can handle.
If the run-time system searches all the methods on the call stack and couldn‟t have found
the appropriate handler, then the run-time system handover the Exception Object to
the default exception handler, which is part of the run-time system. This handler prints
the exception information in the following format and terminates the
program abnormally.
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.
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.
Syntax of 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{}
Common checked exceptions
Many checked exceptions arise when the program cannot find items it expects to exist. These
exceptions use phrases like NotFound or NoSuch in their name and are part of the
ReflectiveOperationException subclass.
ClassNotFoundException: This is one of the most common exceptions in Java. There are
several situations where a ClassNotFound exception can occur, including:
Java Classloader or Class.forName() methods cannot find a specified class in the classpath
when attempting to load the class.
Attempting to load Java database connectivity (JDBC) files using Class.forName() if the jar
file is not in the class‟s path
It is simple to set up a test of the ClassNotFound exception using a try-catch block. The try-
catch block is specifically intended to identify potential exceptions.
Example:
try {
Class.forName("FindMissingClass");
}
ex.printStackTrace();
}
}}
Example:
class ExceptionTest{
public void method1(String firstString)
{
System.out.println(firstString)
}}
public class BadMethodCall{
public static void main(string[] args)
{
ExceptionTest obj = new ExceptionTest();
obj.method1("This is the first method");
obj.method2("This is the missiong method");
}}
Interrupted Exception
Java throws an InterruptedException if a thread that is either occupied or not currently active
(e.g., sleeping or waiting) is interrupted. You can create an interruption to show how this
exception works:
ex.printStackTrace();
}
}}
public class InterruptedExceptionTest {
Example:
Java Exception Keywords: Java provides five keywords that are used to handle the exception.
The following table describes each.
Keyword Description
try The "try" keyword is used to specify a block where we should place an exception
code. It means we can't use try block alone. The try block must be followed by
either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try block
which means we can't use catch block alone. It can be followed by finally block
later.
finally The "finally" block is used to execute the necessary code of the program. It is
executed whether an exception is handled or not.
throws The "throws" keyword is used to declare exceptions. It specifies that there may
occur an exception in the method. It doesn't throw an exception. It is always used
with method signature.
Throw: The throw keyword is used to throw an exception explicitly. Only object of Throwable
class or its sub classes can be thrown. Program execution stops onencountering throw statement,
and the closest catch statement is checked for matching type of exception.
Syntax : throw throwable instance
New NullPointException(“test”)
In this example, we are throwing Arithmetic exception explicitly by using the throw keyword
that will be handle by catch block.
class Test{
static void avg()
{
try
{
throw new ArithmeticException("demo");
}
catch(ArithmeticException e)
{
System.out.println("Exception caught");
}
}
The throws keyword is used to declare the list of exception that a method may throw during
execution of program. Any method that is capable of causing exceptions must list all the
exceptions possible during its execution, so that anyone calling that method gets a prior
knowledge about which exceptions are to be handled. A method can do so by using
the throws keyword.
To prevent this compile time error we can handle the exception in two ways:
1. By using try catch
2. By using throws keyword
Syntax: type method_name(parameters) throws exception_list
Example
// Java program to illustrate error in case
// of unhandled exception
class tst
{
public static void main(String[] args)
{
Thread.sleep(10000);
System.out.println("Hello Java!");
}
}
Output:
error: unreported exception InterruptedException; must be caught or declared to be thrown
Explanation : In the above program, we are getting compile time error because there is a chance
of exception if the main thread is going to sleep, other threads get the chance to execute main()
method which will cause InterruptedException.
Example throws to correct the Error
// Java program to illustrate throws
class tst
{
public static void main(String[] args)throws InterruptedException
{
Thread.sleep(10000);
System.out.println("Hello Java!);
}
}
Output: Hello Java!
Another Example: To Handle IllegalAccessException
class ThrowsExecp
{
static void fun() throws IllegalAccessException
{
System.out.println("Inside fun(). ");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
try
{
fun();
}
catch(IllegalAccessException e)
{
System.out.println("caught in main.");
}}}
Output: Inside fun().
caught in main.
Example of throws: To ArithmeticException
Here, we have a method that can throw Arithmetic exception so we mentioned that with the
method declaration and catch that using the catch handler in the main method.
class Test{
static void check() throws ArithmeticException
{
System.out.println("Inside check function");
throw new ArithmeticException("demo");
}
public static void main(String args[])
{
try
{
check();
}
catch(ArithmeticException e)
{
System.out.println("caught" + e);
}
}}
Output: Inside check function caughtjava.lang.ArithmeticException: demo
Important points about throws keyword:
throws keyword is required only for checked exception and usage of throws keyword for
unchecked exception is meaningless.
throws keyword is required only to convince compiler and usage of throws keyword does
not prevent abnormal termination of program.
By the help of throws keyword we can provide information to the caller of the method about
the exception.
Throws
Throw
throw keyword is declared inside a throws keyword is used with method signature
method body. (method declaration).
A finally keyword is used to create a block of code that follows a try block. A finally block of
code is always executed whether an exception has occurred or not. Using a finally block, it lets
you run any cleanup type statements that you want to execute, no matter what happens in the
protected code. A finally block appears at the end of catch block.
A finally block contains all the crucial statements that must be executed whether exception
occurs or not. The statements present in this block will always execute regardless of whether
exception occurs in try block or not such as closing a connection, stream etc.
try {
//Statements that may cause an exception
}
catch {
//Handling exception
}
finally {
//Statements to be executed
}
Note: If you don't handle the exception, before terminating the program, JVM executes
finally block (if any).
Example 1:
Here you can see that the exception occurred in try block which has been handled in catch block,
after that finally block got executed.
class Example
{
public static void main(String args[]) {
try{
int num=121/0;
System.out.println(num);
}
catch(ArithmeticException e){
System.out.println("Number should not be divided by zero");
}
finally{
System.out.println("This is finally block");
}
System.out.println("Out of try-catch-finally");
}
}
Output: Number should not be divided by zero
Out of try-catch-finally
Example 2:
In this example, we are using finally block along with try block. This program throws an
exception and due to exception, program terminates its execution but see code written inside the
finally block executed. It is because of nature of finally block that guarantees to execute the code.
class Demo{
public static void main(String[] args)
{
int a[] = new int[2];
try
{
System.out.println("Access invalid element"+ a[3]);
/* the above statement will throw ArrayIndexOutOfBoundException */
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught");
}
finally
{
System.out.println("finally is always executed.");
}
}}
You can see that even though we have return statement in the method, the finally block still runs.
class JavaFinally
{
public static void main(String args[])
{
System.out.println(JavaFinally.myMethod());
}
public static int myMethod()
{
try {
return 112;
}
finally {
System.out.println("This is Finally block");
System.out.println("Finally block ran even after return statement");
}
}
}
1. A finally block must be associated with a try block, you cannot use finally without a try block.
You should place those statements in this block that must be executed always.
2. Finally block is optional, as we have seen in previous tutorials that a try-catch block is
sufficient for exception handling, however if you place a finally block then it will always run
after the execution of try block.
3. In normal case when there is no exception in try block then the finally block is executed after
try block. However if an exception occurs then the catch block is executed before finally block.
4. An exception in the finally block, behaves exactly like any other exception.
5. The statements present in the finally block execute even if the try block contains control
transfer statements like return, break or continue.
Java provides us facility to create our own exceptions which are basically derived classes
of Exception. For example MyException in below code extends the Exception class. We pass the
string to the constructor of the super class- Exception which is obtained using “getMessage()”
function on the object created.
1. printStackTrace(): This method prints exception information in the format of the Name of
the exception: description of the exception, stack trace.
2. toString(): The toString() method prints exception information in the format of the Name of
the exception: description of the exception.
3. getMessage(): The getMessage() method prints only the description of the exception.
4.Public String getLocalizedMessage() – This method is provided so that subclasses can
override it to provide locale specific message to the calling program. Throwable class
implementation of this method simply use getMessage() method to return the exception message.
5. Public synchronized Throwable getCause() – This method returns the cause of the
exception or null id the cause is unknown.
Example 1:
//program to print the exception information using printStackTrace() method
import java.io.*;
class GFG {
public static void main (String[] args) {
int a=5;
int b=0;
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
e.printStackTrace();
}
}
}
Output:
java.lang.ArithmeticException: / by zero
at GFG.main(File.java:10)
Example 2:
//program to print the exception information using toString() method
import java.io.*;
class GFG1 {
public static void main (String[] args) {
int a=5;
int b=0;
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
System.out.println(e.toString());
}
}
}
Output: java.lang.ArithmeticException: / by zero
Example:
//program to print the exception information using getMessage() method
import java.io.*;
class GFG1 {
public static void main (String[] args) {
int a=5;
int b=0;
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
System.out.println(e.getMessage());
}
}
}
Output: / by zero
The advantages of Exception Handling in Java are as follows: