0% found this document useful (0 votes)
12 views46 pages

Lecture 5

Uploaded by

omr2002020
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)
12 views46 pages

Lecture 5

Uploaded by

omr2002020
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

OOP: Exception Handling

Dr. Fayçal Hamdi


Faculty of Computer Science & Information Systems
Islamic University, Madinah, SA
[email protected]
Exception Handling in Java
• Def: 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 (EH) in Java is one of the powerful
mechanism to handle the runtime errors such as
ClassNotFoundException, IOException, SQLException,
RemoteException, etc., so that the normal flow of the
application can be maintained.
• Effect of EH: Suppose there are 10 statements in a Java
program and an exception occurs at statement 5; the rest of
the code will not be executed, i.e., statements 6 to 10 will not
be executed. However, when we perform exception handling,
the rest of the statements will be executed. That is why we
use exception handling in Java.
Exception Classes Hierarchy
• The java.lang.Throwable class is the root
and inherited by two subclasses:
Exception and Error. The hierarchy of
Java Exception classes is given:
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:
Difference between Checked and
Unchecked Exceptions
• Checked Exception
• Def: The classes that directly inherit the Throwable class except RuntimeException
and Error, are known as checked exceptions. For example, IOException,
SQLException, ClassNotFoundException.
• Checked exceptions are checked at compile-time.
• Unchecked Exception
• Def: The classes that inherit the RuntimeException are known as unchecked
exceptions. For example, ArithmeticException, NullPointerException,
NumberFormatException, IndexOutOfBoundsException, etc.
• Unchecked exceptions checked at runtime.
• Error
• Def: Error is irrecoverable at runtime. For example: OutOfMemoryError,
VirtualMachineError, StackOverflowError, etc.
Java Exception Keywords
• Java provides five keywords that are used to handle the exception.
Keyword Description

Used to specify a block where we can place source code expecting the exception. The try
try
block must be followed by either catch or finally.

Used to handle the exception occurred in try block. Must be preceded by try block and can
catch
be followed by finally block later.

Used to execute the necessary code of the program whether an exception is handled or
finally
not.
throw Used to throw an exception event.

Used to declare exceptions. It doesn't throw an exception rather specifies that there may
throws
occur an exception in the method. It is always used with method signature.
Java Exception Handling Example
• Using a try-catch statement to handle the Arithmetic Exception.
Common Scenarios of Java Exceptions
• If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0; //ArithmeticException
• 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
• If the formatting of any variable or number is mismatched, it may result into
NumberFormatException.
String s="abc"; //must have digits as string
int i=Integer.parseInt(s); //NumberFormatException
• When an array exceeds to it's size, the ArrayIndexOutOfBoundsException
occurs.
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
Java Exceptions Index
1.Java Try-Catch Block
2.Java Multiple Catch Block
3.Java Nested Try
4.Java Finally Block
5.Java Throw Keyword
6.Java Exception Propagation
7.Java Throws Keyword
8.Java Throw vs Throws
9.Java Final vs Finally vs Finalize
10.Java Exception Handling with Method Overriding
11.Java Custom Exceptions
1. Java try-catch block
• Def: 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.
1. Java try-catch block
• Def: 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.
Problem without exception handling
• As displayed in LHS, the
rest of the code statement is
not printed).
• As displayed in RHS, the
rest of the code statement is
printed.
Example 1
• In this LHS example,
we also kept the code
in a try block that will
not be executed after
the throw of an
exception.
• Here in RHS, we
handle the exception
using the parent class
exception.
Example 2
• LHS is an example to print
a custom message on
exception.

• RHS is an example to
resolve the exception in a
catch block.
Example 3
• LHS: Useless exception
code in catch. So,
enclose exception code
within a try block and
use catch block only to
handle the exceptions.
• RHS: Wrong exception
handling. When the
generated exception
(Arithmetic Exception)
with a different type of
exception class
(ArrayIndexOutOfBoun
dsException).
Example 4
• Another unchecked
exception. (LHS)

• Another checked
exception. (RHS)
2. Java Catch Multiple Exceptions
• 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.
• 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.
Example 1
• LHS: Finding match at
the first catch.

• RHS: Finding match at


the second catch
Example 2

• (LHS): is the case of


not finding the
match
NullPointerExceptio
n, and then the
parent exception
class Exception is
invoked.

• RHS: Exceptions
without maintaining
the order from most
specific to most
general
3. 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 context of that exception is
pushed onto the stack.
• 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 1 • Let's see an example
where we place a try
block within another try
block for two different
exceptions.
Example 2
• When the try block within nested
try block (inner try block 2) does
not handle the exception. The
control is then transferred to its
parent try block (inner try block
1).
4. Java Finally Block
• Java finally block is a block used to execute
important code (clean-up code) such as closing
the connection, closing the file, etc.
• Java finally block is always executed whether an
exception is handled or not.
• The finally block follows the try-catch block.
• Flow Diagram of Java Finally Block (RHS)

• Note: If you don't handle the exception, before


terminating the program, JVM executes
finally block (if any).
Example
• Case 1 (LHS) : When an
exception does not occur

• Case 2 (RHS): When an


exception occur but not
handled by the catch block
• Case 3 (LHS): When an exception occurs and is
handled by the catch block
Example

• Rule: For each try block there can be one or more catch
blocks, but only one finally block.

• Note: The finally block will not be executed if the


program exits (either by calling System.exit() or by
causing a fatal error that causes the process to abort).
5. 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.
• 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. 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 as follows.
5. Java throw Exception

• 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.
Example 1: Throwing Unchecked/Checked
Exception
• In this example, we have created
the validate method that takes
integer value as a parameter. If the
age is less than 18, we are
throwing the ArithmeticException
otherwise print a message welcome
to vote. (LHS). If we throw
unchecked exception from a
method, it is must to handle the
exception or declare in throws
clause. (LHS)
• 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. (RHS)
Example 2: Throwing User-defined
Exception
6. Java Exception Propagation
• An exception is first thrown from the top
of the stack and if it is not caught, it keeps
on dropping down the call stack to the
previous methods sequentially until
caught or until reached the very bottom of
the call stack. This is called exception
propagation.
• LHS: Exception occurs in the m() method
but not handled, so propagated to the
previous n() method again not handled, so
propagated to the p() method where the
exception is handled.

• Note: RHS: Checked Exceptions are not


forwarded in calling chain (propagated)
by default but unchecked exceptions are.
7. Java throws keyword
• The Java throws keyword is used to declare an exception and it gives an
information that there may occur an exception. So, it is better to provide the
exception handling code so that the normal flow of the program can be
maintained.
• Syntax of Java throws (On RHS)
• 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.
• Advantage of Java throws keyword
• Checked Exception can be propagated (forwarded in call stack) due to effect of throws
(Example next on LHS)
• It provides information to the caller of the method about the exception.
Java throws Example
• Rule: If we are calling a method
that declares an exception, we
must either catch (Case 1) or
declare (Case 2) the exception.

• There are two cases:


• Case 1: Catch and handled
using try/catch block (LHS
& RHS).

• Case 2: Declared the


exception only using throws
keyword (next slide).
Java throws Example
• Case 2: Declare Exception
• In case we declare the
exception,
• If exception does not occur,
the code will be executed
fine. (LHS)
• If the exception occurs, it will
be thrown at runtime because
throws does not handle the
exception. (RHS)
8. Difference between throw and throws
(Self Studies)
Sr.
Basis of Differences throw throws
no.

Java throws keyword is used in the method


Java throw keyword is used to throw an
signature to declare an exception which
1. Definition exception explicitly in the code, inside
might be thrown by the function while the
the function or the block of code.
execution of the code.
Using throws keyword, we can declare both
Using throw keyword, we can only checked and unchecked exceptions.
propagate unchecked exception i.e., the However, the throws keyword can be used
2. Type of exception
checked exception cannot be to propagate checked exceptions only.
propagated using throw only.

The throw keyword is followed by an The throws keyword is followed by class


3. Syntax
instance of Exception to be thrown. names of Exceptions to be thrown.
4. Declaration throw is used within the method. throws is used with the method signature.
We can declare multiple exceptions using
We are allowed to throw only one
throws keyword that can be thrown by the
5. Internal implementation exception at a time i.e. we cannot throw
method. For example, main() throws
multiple exceptions.
IOException, SQLException.
8. Difference between throw and throws
(Self Studies)
• Java throw Example
(LHS)
• Java throws Example
(RHS)
8. Difference between throw and throws
(Self Studies)
• Java throw and throws
Example
9. Difference between final, finally and finalize
(Self Studies)
Sr. no. Key final finally finalize
finalize is the method in
final is the keyword and access finally is the block in Java Exception Java which is used to
modifier which is used to apply Handling to execute the important perform clean up
1. Definition
restrictions on a class, method or code whether the exception occurs processing just before
variable. or not. object is garbage
collected.
Finally block is always related to the
Final keyword is used with the classes, finalize() method is
2. Applicable to try and catch block in exception
methods and variables. used with the objects.
handling.
(1) Once declared, final variable
(1) finally block runs the important finalize method
becomes constant and cannot be
code even if exception occurs or performs the cleaning
modified.
3. Functionality not. activities with respect
(2) final method cannot be overridden
(2) finally block cleans up all the to the object before its
by sub class.
resources used in try block destruction.
(3) final class cannot be inherited.
Finally block is executed as soon as
finalize method is
Final method is executed only when the try-catch block is executed.It's
4. Execution executed just before the
we call it. execution is not dependant on the
object is destroyed.
exception.
9. Difference between final, finally and finalize
(Self Studies)
• Java final Example
• Let's consider the following example
where we declare final variable age.
Once declared it cannot be modified.
(LHS)
• In the above example, we have
declared a variable final. Similarly, we
can declare the methods and classes
final using the final keyword.
• Java finally Example
• Let's see the below example where the
Java code throws an exception and the
catch block handles that exception.
Later the finally block is executed
after the try-catch block. Further, the
rest of the code is also executed
normally. (RHS)
9. Difference between final, finally and finalize
(Self Studies)
• Java finalize Example
10. Exception Handling with Method
Overriding in Java
(Self Studies)
• There are many rules if we talk about method
overriding with exception handling.
• Rule 1(a): If the superclass method does not
declare an exception, subclass overriding
method cannot declare the checked exception
(LHS)
• Rule 1(b): If the superclass method does not
declare an exception, subclass overriding
method cannot declare the checked exception
but can declare unchecked exception. (RHS)
10. Exception Handling with Method
Overriding in Java
(Self Studies)
• Rule 2(a): If the superclass method
declares an exception, subclass
overridden method can declare the
same, subclass exception or no
exception but cannot declare parent
exception.
• Example in case subclass overridden
method declares illegal parent
exception (LHS)
• Example in case subclass overridden
method declares same exception
(RHS)
10. Exception Handling with Method
Overriding in Java
(Self Studies)
• Example in case subclass overridden
method declares subclass exception
(LHS)
• Example in case subclass overridden
method declares no exception (RHS)
11. Java Custom Exception
• Creating our own Exception is known as Custom Exception or User-Defined
Exception.
• Why use custom exceptions?
• We sometimes need to create exceptions with our own custom messages.
• We can create custom exception by extending Exception class that belongs to
java.lang package. For example, creating a custom exception named
“WrongFileNameException”
• Note: We need to write the constructor that takes the String as the error message
and it is called parent class constructor.
11. Java Custom Exception
• Example 1:
• Let's see a simple example of
Java custom exception. In the
following code, constructor of
InvalidAgeException takes a
string as an argument. This
string is passed to constructor
of parent class Exception
using the super() method.
11. Java Custom Exception
• Example 2: Custom Exception with Null message

You might also like