[go: up one dir, main page]

0% found this document useful (0 votes)
36 views20 pages

OOP - Chapter 4-Exception Handling

Uploaded by

abduwasi ahmed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views20 pages

OOP - Chapter 4-Exception Handling

Uploaded by

abduwasi ahmed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

MIZAN-TEPI UNIVERSITY

SCHOOL OF COMPUTING AND INFORMATICS


DEPARTMENT OF INFORMATION SYSTEMS

Course: Object-Oriented Programming | JAVA (InSy2042)

Class: BSc. Second Year – 2nd Semester (Regular)

Academic Year: 2016 |2023

Chapter Four - 4: Exception Handling

By: Rashid W.

November 2023
Tepi, Ethiopia
OOP | Unit Four-4: Exception Handling

Chapter 4 Four- Exception Handling

4.1 Overview of Exception Handling


The Exception Handling is one of the powerful mechanism to handle the runtime errors so that
the normal flow of the application can be maintained.
Exception is an error event that can happen during the execution of a program and disrupts its
normal flow. Java provides a robust and object-oriented way to handle exception scenarios,
known as Java Exception Handling.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.
Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException,
IOException, SQLException, RemoteException, etc.
The core advantage of exception handling is to maintain the normal flow of the application.
When an exception occurs within a method, it creates an object. This object is called the
exception object.
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of
memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc.
Errors are usually beyond the control of the programmer, and we should not try to handle
errors.

Difference between Error and Exception

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

By: Rashid W. @ MTU_SCI_IS_2nd Year 2


OOP | Unit Four-4: Exception Handling

Fig 4.1 Java Exception Hierarchy

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.

Exceptions can be categorized in two ways:

1. Built-in Exceptions
 Checked Exception
 Unchecked Exception
2. User-Defined Exceptions
3. Error

By: Rashid W. @ MTU_SCI_IS_2nd Year 3


OOP | Unit Four-4: Exception Handling

Fig 4.2 Types of Exceptions in Java

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.

 Checked Exceptions: Checked exceptions are called compile-time exceptions because


these exceptions are checked at compile-time by the compiler. The classes that directly
inherit the Throwable class except RuntimeException and Error are known as checked
exceptions. For example, IOException, SQLException, etc.

 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‟.

By: Rashid W. @ MTU_SCI_IS_2nd Year 4


OOP | Unit Four-4: Exception Handling

3.Error: Error is irrecoverable. Some example of errors are OutOfMemoryError,


VirtualMachineError, AssertionError etc.

Common Scenarios of Java Exceptions

There are given some scenarios where unchecked exceptions may occur. They are as follows:

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.

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.

int a[]=new int[5];


a[10]=50; //ArrayIndexOutOfBoundsException

4.2 Handling of an Exception


Handling of an Exception in Java is takes place in two ways, they are:
 JVM Handle an Exception by Default
 Programmer Handle an Exception
How Does JVM Handle an Exception (Default Exception Handling)?

By: Rashid W. @ MTU_SCI_IS_2nd Year 5


OOP | Unit Four-4: Exception Handling

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.

How Programmer Handle an Exception (Customized Exception Handling)?

Customized Exception Handling: Java exception handling is managed via five


keywords: try, catch, throw, throws, and finally. Briefly, here is how they work. Program
statements that you think can raise exceptions are contained within a try block. If an exception
occurs within the try block, it is thrown. Your code can catch this exception (using catch
block) and handle it in some rational manner. System-generated exceptions are automatically
thrown by the Java run-time system. To manually throw an exception, use the keyword throw.
Any exception that is thrown out of a method must be specified as such by a throws clause.
Any code that absolutely must be executed after a try block completes is put in a finally block.

By: Rashid W. @ MTU_SCI_IS_2nd Year 6


OOP | Unit Four-4: Exception Handling

Java try…catch Block

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:

public class ExceptionTest {

public static void main(String args[])

By: Rashid W. @ MTU_SCI_IS_2nd Year 7


OOP | Unit Four-4: Exception Handling

try {

Class.forName("FindMissingClass");
}

catch (ClassNotFoundException ex) {

ex.printStackTrace();
}
}}

NoSuchMethodException: Java throws a NoSuchMethod exception when attempting to call a


non-existent class method or a private method. A simple example shows how this exception can
arise when a developer is not careful about defining and using method names.

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:

class InterruptedThread extends Thread {

public void run() {


try {
Thread.sleep(100);
}
catch (InterruptedException ex) {

By: Rashid W. @ MTU_SCI_IS_2nd Year 8


OOP | Unit Four-4: Exception Handling

ex.printStackTrace();
}
}}
public class InterruptedExceptionTest {

public static void main(String[] args) {


InterruptedThread sleepingthread = new InterruptedThread();
sleepingthread.start();
sleepingthread.interrupt();
}}

InvocationTargetException: This exception is actually an indicator of an underlying


exception in a method. Java throws the exception when an attempt is made to invoke a method
that throws the primary exception. InvocationTargetException does not provide specifics on the
underlying exception, although developers can use the getCause() method for further
information.
Common unchecked exceptions
Recall that unchecked examples only arise at runtime rather than appearing during compilation.

IllegalArgumentException: An illegal argument exception is thrown when input to a method is


of the wrong type; for example, an array is passed when the method accepts only integer input or
if the input is out of a specified input range. You can use the throw exception statement or try-
catch blocks to create error messages if a user submits improper input data.
Similar exceptions exist for various other conditions, such as ArrayIndexOutofBoundException
or NumberFormatException.
ArithmeticException: As its name implies, Java throws this exception if the program attempts
an arithmetic operation that is inconsistent with Java operations. The most common example is
dividing by zero.

Example:

public class ExceptionTest {

public static void main(String[] args) {


try {
int divbyzero = 1/0;
}
catch (ArithmeticException ex) {
ex.printStackTrace();

By: Rashid W. @ MTU_SCI_IS_2nd Year 9


OOP | Unit Four-4: Exception Handling

System.out.println("ERROR: Divide by zero");


}
}}

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.

throw The "throw" keyword is used to throw an exception.

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.

4.3 The Causes of Exceptions

Major reasons why an exception Occurs

 Invalid user input


 Device failure
 Loss of network connection
 Physical limitations (out-of-disk memory)
 Code errors
 Opening an unavailable file
A java exception can be thrown only in the following three scenarios:
(1) An abnormal execution condition was synchronously detected by the Java virtual machine.
• When evaluation of an expression violates the normal semantics (Example: an integer divide
by zero)

By: Rashid W. @ MTU_SCI_IS_2nd Year 10


OOP | Unit Four-4: Exception Handling

• An error occurs in loading or linking part of the program


• When limitation on a resource is exceeded (Example: using too much memory)
(2) A throw statement was executed.
(3) An asynchronous exception occurred.
• The stop method (deprecated) of class Thread was invoked
• An internal error has occurred in the java virtual machine
4.4 The Throw Statement and The Finally Clause
Java throw, throws and finally Keyword
Throw, throws and finally are the keywords in Java that are used in exception handling. The
throw keyword is used to throw an exception and throws is used to declare the list of possible
exceptions with the method signature. Whereas finally block is used to execute essential code,
specially to release the occupied resources.

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

Creating Instance of Throwable class

We allows to use new operator to create an instance of class Throwable,

New NullPointException(“test”)

This constructs an instance of NullPointerException with name test.

Example throw Exception

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");
}
}

By: Rashid W. @ MTU_SCI_IS_2nd Year 11


OOP | Unit Four-4: Exception Handling

public static void main(String args[])


{
avg();
}}
In the above example the avg() method throw an instance of ArithmeticException, which is
successfully handled using the catch statement and thus, the program prints the output
"Exception caught".

Java throws Keyword

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

By: Rashid W. @ MTU_SCI_IS_2nd Year 12


OOP | Unit Four-4: Exception Handling

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
{

By: Rashid W. @ MTU_SCI_IS_2nd Year 13


OOP | Unit Four-4: Exception Handling

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.

Difference between throw and throws

Throws
Throw

 throw keyword is used to throw an  throws keyword is used to declare an exception


exception explicitly. possible during its execution.

 throw keyword is followed by an


 throws keyword is followed by one or more
instance of Throwable class or one of its
Exception class names separated by commas.
sub-classes.

 throw keyword is declared inside a  throws keyword is used with method signature
method body. (method declaration).

 We cannot throw multiple exceptions  We can declare multiple exceptions (separated by


using throw keyword. commas) using throws keyword.

The finally clause

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.

By: Rashid W. @ MTU_SCI_IS_2nd Year 14


OOP | Unit Four-4: Exception Handling

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.

Syntax of Finally block

try {
//Statements that may cause an exception
}
catch {
//Handling exception
}
finally {
//Statements to be executed
}

Flowchart of finally block

By: Rashid W. @ MTU_SCI_IS_2nd Year 15


OOP | Unit Four-4: Exception Handling

 Note: If you don't handle the exception, before terminating the program, JVM executes
finally block (if any).

 The three Conditions in whichFinally Block or Clause is Executed

Case1: When an exception does not occur


Case 2: When an exception occurr but not handled by the catch block
Case 3: When an exception occurs and is handled by the catch block

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

This is finally block

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.

By: Rashid W. @ MTU_SCI_IS_2nd Year 16


OOP | Unit Four-4: Exception Handling

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.");
}
}}

Example 3: finally block and return statement

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");
}
}
}

Important points about finally block

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.

By: Rashid W. @ MTU_SCI_IS_2nd Year 17


OOP | Unit Four-4: Exception Handling

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.

4.5 User Defined Exceptions

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.

Methods to print the Exception information:

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.*;

By: Rashid W. @ MTU_SCI_IS_2nd Year 18


OOP | Unit Four 4: Exception Handling

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{

By: Rashid W. @ IS_2nd Year 19


OOP | Unit Four 4: Exception Handling

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:

1. Provision to Complete Program Execution


2. Easy Identification of Program Code and Error-Handling Code
3. Propagation of Errors
4. Meaningful Error Reporting
5. Identifying Error Types

By: Rashid W. @ IS_2nd Year 20

You might also like