2024
Exception Handling Part 1
IF2304 – Object Oriented Programming
BACK EXCEPTION HANDLING 01
Overview
Part 13: Exception Handling Part 1. This chapter provides an introduction to exception handling
in Java, covering fundamental concepts such as try-catch, try-catch-finally, throw, and throws
statements.
BACK EXCEPTION HANDLING 02
Objectives
After completing this chapter, you should be able to:
• Understand the basics of exception handling in Java.
• Implement try-catch blocks to handle exceptions effectively.
• Utilize try-catch-finally blocks to manage resources and ensure cleanup.
• Apply the 'throw' keyword to manually throw exceptions.
• Implement the 'throws' clause to specify exceptions that can be thrown by a method.
BACK EXCEPTION HANDLING 03
• Exception Handling
Content
• try-catch
• try-catch-finally
• throw
• throws
BACK EXCEPTION HANDLING 04
Exception
BACK EXCEPTION HANDLING 05
Exception
• The class Exception and its subclasses are a form of Throwable that
indicates conditions that a reasonable application might want to catch.
• Since an Exception is a class, when a program runs and encounters a bug
or error, that bug can be considered an object.
• So, when this object is displayed on the screen, Java will automatically
invoke the toString method found within this Exception object.
• Java provides developers access to retrieve this occurred bug object
through a mechanism known as Exception Handling.
• Exception handling is a feature in Java that gives developers flexibility to
capture bugs or errors that occur during program execution.
BACK EXCEPTION HANDLING 06
Exception : 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
BACK EXCEPTION HANDLING 07
Exception = Error?
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.
Let us discuss the most important part which is the differences between
Error and Exception that is as follows :
• 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.
BACK EXCEPTION HANDLING 08
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.
BACK EXCEPTION HANDLING 09
Exception : Hierarchy
BACK EXCEPTION HANDLING 10
Exception : Types
Java defines several types of exceptions that relate to its various class
libraries. Java also allows users to define their own exceptions.
BACK EXCEPTION HANDLING 11
Exception : 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.
• Unchecked Exceptions : The unchecked exceptions are just opposite to
the checked exceptions. 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.
BACK EXCEPTION HANDLING 12
Exception : Built-in Exceptions
Built-in exceptions are the exceptions that are available in Java libraries.
These exceptions are suitable to explain certain error situations. Below is
the list of important built-in exceptions in Java.
• ArithmeticException : It is thrown when an exceptional condition has
occurred in an arithmetic operation.
• ArrayIndexOutOfBoundsException : It is thrown to indicate that an array
has been accessed with an illegal index. The index is either negative or
greater than or equal to the size of the array.
• ClassNotFoundException : This Exception is raised when we try to access
a class whose definition is not found.
BACK EXCEPTION HANDLING 13
Exception : Built-in Exceptions
• FileNotFoundException : This Exception is raised when a file is not
accessible or does not open.
• IOException : It is thrown when an input-output operation failed or
interrupted
• InterruptedException : It is thrown when a thread is waiting, sleeping, or
doing some processing, and it is interrupted.
• NoSuchFieldException : It is thrown when a class does not contain the
field (or variable) specified
• NoSuchMethodException : It is thrown when accessing a method that is
not found.
BACK EXCEPTION HANDLING 14
Exception : Built-in Exceptions
• NullPointerException : This exception is raised when referring to the
members of a null object. Null represents nothing
• NumberFormatException : This exception is raised when a method could
not convert a string into a numeric format.
• RuntimeException : This represents an exception that occurs during
runtime.
• StringIndexOutOfBoundsException : It is thrown by String class methods
to indicate that an index is either negative or greater than the size of the
string.
BACK EXCEPTION HANDLING 15
Exception : Built-in Exceptions
• IllegalArgumentException : This exception will throw the error or error
statement when the method receives an argument which is not
accurately fit to the given relation or condition. It comes under the
unchecked exception.
• IllegalStateException : This exception will throw an error or error
message when the method is not accessed for the particular operation in
the application. It comes under the unchecked exception.
BACK EXCEPTION HANDLING 16
Exception : 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’.
The advantages of Exception Handling in Java are as follows :
• Provision to Complete Program Execution
• Easy Identification of Program Code and Error-Handling Code
• Propagation of Errors
• Meaningful Error Reporting
• Identifying Error Types
BACK EXCEPTION HANDLING 17
Exception : How Programmer Handle an Exception?
Java exception handling is
managed via five keywords :
try, catch, throw, throws, and
finally.
BACK EXCEPTION HANDLING 18
try-catch
BACK EXCEPTION HANDLING 19
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.
BACK EXCEPTION HANDLING 20
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.
BACK EXCEPTION HANDLING 21
Internal Working of Java try-catch block
BACK EXCEPTION HANDLING 22
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.
BACK EXCEPTION HANDLING 23
Problem Example
Let's try to understand the problem if we don't use a try-catch block.
Output :
• As displayed in the above example, the rest of the code is not executed (in
such case, the rest of the code statement is not printed).
• There might be 100 lines of code after the exception. If the exception is not
handled, all the code below the exception won't be executed.
BACK EXCEPTION HANDLING 24
Solution by Exception Handling : try-catch
Output : Output :
BACK EXCEPTION HANDLING 25
try-catch-finally
BACK EXCEPTION HANDLING 26
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.
BACK EXCEPTION HANDLING 27
Flowchart of finally block
BACK EXCEPTION HANDLING 28
Why use 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.
BACK EXCEPTION HANDLING 29
Usage of Java finally
• Case 1 : When an exception does not occur
Output :
BACK EXCEPTION HANDLING 30
Usage of Java finally
• Case 2 : When an exception occur but not handled by the catch block
Output :
BACK EXCEPTION HANDLING 31
Usage of Java finally
• Case 3 : When an exception occurs and is handled by the catch block
Output :
BACK EXCEPTION HANDLING 32
throw
BACK EXCEPTION HANDLING 33
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.
BACK EXCEPTION HANDLING 34
throw keyword
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.
The syntax of the Java throw keyword is given below.
throw Instance i.e.,
BACK EXCEPTION HANDLING 34
throw keyword Example
Let's see the example of throw IOException.
Where the Instance must be of type Throwable or subclass of Throwable.
For example, Exception is the sub class of Throwable and the user-defined
exceptions usually extend the Exception class.
Read more in here.
BACK EXCEPTION HANDLING 35
throws
BACK EXCEPTION HANDLING 36
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.
BACK EXCEPTION HANDLING 37
throws keyword : Which exception should be declared?
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.
BACK EXCEPTION HANDLING 38
throws keyword Example
Output :
BACK EXCEPTION HANDLING 39
throws keyword Rule
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.
Read more in here.
BACK EXCEPTION HANDLING 40
Unit Summary
You should now be able to :
• Understand the basics of exception handling in Java.
• Implement try-catch blocks to handle exceptions effectively.
• Utilize try-catch-finally blocks to manage resources and ensure cleanup.
• Apply the 'throw' keyword to manually throw exceptions.
• Implement the 'throws' clause to specify exceptions that can be thrown by a method.
Question & Answer
BACK 2024