java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...
catch Java Nested try block Java try...finally blo
Object Oriented
Programming
Module 3: Exception handling
Dr. Nikhil Mhala
[email protected]
School of Computer Science and Engineering (SCOPE)
VIT-AP University (Besides AP Secretariat) 522237
May 15, 2022
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 1 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Agenda I
1 java Exceptions 8 Java try...catch...finally block
2 Java Exception Hierarchy 9 Java catch Multiple Excep-
3 Types of Exception in Java tions
4 Java Exception Handling 10 Java Throw and throws
5 Java try...catch 11 User-defined exceptions
6 Java Nested try block (Custom Exception)
7 Java try...finally block 12 Java Garbage Collection
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 2 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Java Exceptions
An exception is an unexpected event that occurs during pro-
gram execution. It affects the flow of the program instructions which
can cause the program to terminate abnormally.
An exception can occur for many reasons. Some of them are:
Invalid user input
Device failure
Loss of network connection
Physical limitations (out of disk memory)
Code errors
Opening an unavailable file
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 3 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
What is Exception in Java?
Dictionary Meaning: Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the
program. It is an object which is thrown at runtime.
What is Exception Handling?
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException,
RemoteException, etc.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal
flow of the application. An exception normally disrupts the normal
flow of the application; that is why we need to handle exceptions.
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 4 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Java Exception Hierarchy
The java.lang.Throwable class is the root class of Java Excep-
tion hierarchy inherited by two subclasses: Exception and Error.
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 5 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Types of Exception in Java
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 6 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Types of Exception in Java
Built-in Exceptions
Built-in exceptions are the exceptions which are available in Java
libraries. These exceptions are suitable to explain certain error
situations.
User-Defined Exceptions
Sometimes, the built-in exceptions in Java are not able to describe a
certain situation. In such cases, user can also create exceptions
which are called ‘user-defined Exceptions’.
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 7 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Build-in Exceptions
Below is the list of important built-in exceptions in Java
1 ArithmeticException It is thrown when an exceptional condition
has occurred in an arithmetic operation.
2 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.
3 ClassNotFoundException This Exception is raised when we try
to access a class whose definition is not found
4 FileNotFoundException This Exception is raised when a file is
not accessible or does not open.
5 IOException It is thrown when an input-output operation failed
or interrupted
6 InterruptedException It is thrown when a thread is waiting,
sleeping, or doing some processing, and it is interrupted.
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 8 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Build-in Exceptions
1 NoSuchFieldException It is thrown when a class does not
contain the field (or variable) specified
2 NoSuchMethodException It is thrown when accessing a
method which is not found.
3 NullPointerException This exception is raised when referring to
the members of a null object. Null represents nothing
4 NumberFormatException This exception is raised when a
method could not convert a string into a numeric format.
5 RuntimeException This represents any exception which occurs
during runtime.
6 StringIndexOutOfBoundsException It is thrown by String class
methods to indicate that an index is either negative or greater
than the size of the string
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 9 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Types of Java Exceptions
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 10 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Types of Java Exceptions
Checked Exception
The classes that directly inherit the Throwable class except
RuntimeException and Error are known as checked exceptions. For
example, IOException, SQLException, etc. Checked exceptions are
checked at compile-time.
Unchecked Exception
The classes that inherit the RuntimeException are known as
unchecked exceptions. For example, ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException, etc.
Unchecked exceptions are not checked at compile-time, but they are
checked at runtime.
Error
Error is irrecoverable. Some example of errors are
OutOfMemoryError, VirtualMachineError, AssertionError etc.
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 11 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Types of Java Exceptions
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 12 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Example without exception handling
1 public class T r y C a t c h E x a m p l e 1 {
2
3 public static void main ( String [] args ) {
4
5 int divideByZero =50/0; // may throw exception
6
7 System . out . println ( " rest of the code " ) ;
8
9 }
10
11 }
./code/TryCatchExample1.java
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 13 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Common Scenarios of Java Exceptions
A scenario where ArithmeticException occurs
1 int a =50/0; // A r i t h m e t i c E x c e p t i o n
A scenario where NullPointerException occurs
1 String s = null ;
2 System . out . println ( s . length () ) ; // N u l l P o i n t e r E x c e p t i o n
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 14 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Common Scenarios of Java exceptions
A scenario where NumberFormatException occurs
1 String s = " abc " ;
2 int i = Integer . parseInt ( s ) ; // N u m b e r F o r m a t E x c e p t i o n
A scenario where ArrayIndexOutOfBoundsException occurs
1 int a []= new int [5];
2 a [10]=50; // A r r a y I n d e x O u t O f B o u n d s E x c e p t i o n
3
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 15 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Different Approaches to handle exceptions
in Java
try . . . catch block
finally block
throw and throws keyword
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 16 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Java try . . . catch
The try...catch block in Java is used to handle exceptions and
prevents the abnormal termination of the program.
Syntax of try . . . catch block in Java
1 try {
2 // code
3 }
4 catch ( exception ) {
5 // code
6 }
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 17 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Example: Java try...catch block
1 class Main {
2 public static void main ( String [] args ) {
3
4 try {
5 int divideByZero = 50 / 0;
6 System . out . println ( " Rest of code in try block " ) ;
7 }
8
9 catch ( A r i t h m e t i c E x c e p t i o n e ) {
10 System . out . println ( " A r i t h m e t i c E x c e p t i o n = > " + e .
getMessage () ) ;
11 }
12 }
13 }
./code/TryCatchExampleWithException.java
Note: In Java, we can use a try block without a catch block.
However, we cannot use a catch block without a try block.
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 18 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Internal Working of Java try-catch block
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 19 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
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 statement in try block, 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
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 20 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Syntax of Nested try block
1 // main try block
2 try
3 {
4 statement 1;
5 // try catch block within another try block
6 try
7 {
8 statement 3;
9 // try catch block within nested try block
10 try { statement 5; }
11 catch ( Exception e2 )
12 {
13 // exception message }
14 }
15 catch ( Exception e1 )
16 {
17 // exception message }
18 }
19 // catch block of parent ( outer ) try block
20 catch ( Exception e3 )
21 {
22 // exception message }
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 21 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Example of Nested try block
1 public class Nested TryBlo ck {
2 public static void main ( String args []) {
3 // outer try block
4 try {
5 // inner try block 1
6 try {
7 System . out . println ( " going to divide by 0 " ) ;
8 int b =39/0; }
9 // catch block of inner try block 1
10 catch ( A r i t h m e t i c E x c e p t i o n e )
11 {
12 System . out . println ( e ) ; }
13 // inner try block 2
14 try {
15 int a []= new int [5];
16 // assigning the value out of array bounds
17 a [5]=4; }
./code/NestedTryBlock.java
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 22 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Example of Nested try block
18 // catch block of inner try block 2
19 catch ( A r r a y I n d e x O u t O f B o u n d s E x c e p t i o n e )
20 {
21 System . out . println ( e ) ; }
22 System . out . println ( " other statement " ) ;
23 }
24 // catch block of outer try block
25 catch ( Exception e )
26 {
27 System . out . println ( " handled the exception ( outer catch ) "
);
28 }
29 System . out . println ( " normal flow .. " ) ;
30 }
31 }
./code/NestedTryBlock.java
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 23 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Example 2 of Nested try block
1 public class N es te d Tr yB l oc k 2 {
2 public static void main ( String args [])
3 {
4 // outer ( main ) try block
5 try {
6 // inner try block 1
7 try {
8
9 // inner try block 2
10 try {
11 int arr [] = { 1 , 2 , 3 , 4 };
12 // printing the array element out of its
bounds
13 System . out . println ( arr [10]) ;
14 }
15 // to handles A r i t h m e t i c E x c e p t i o n
16 catch ( A r i t h m e t i c E x c e p t i o n e ) {
17 System . out . println ( " Arithmetic exception
");
18 System . out . println ( " inner try block 2 " )
;
19 }
20
Dr. Nikhil Mhala VIT-AP
} CSE2005 May 15, 2022 24 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Example 2 of Nested try block
21
22 // to handle A r i t h m e t i c E x c e p t i o n
23 catch ( A r i t h m e t i c E x c e p t i o n e ) {
24 System . out . println ( " Arithmetic exception " ) ;
25 System . out . println ( " inner try block 1 " ) ;
26 }
27 }
28 // to handle A r r a y I n d e x O u t O f B o u n d s E x c e p t i o n
29 catch ( A r r a y I n d e x O u t O f B o u n d s E x c e p t i o n e4 ) {
30 System . out . print ( e4 ) ;
31 System . out . println ( " outer ( main ) try block " ) ;
32 }
33 catch ( Exception e5 ) {
34 System . out . print ( " Exception " ) ;
35 System . out . println ( " handled in main try - block " )
;
36 }
37 }
38 }
./code/NestedTryBlock2.java
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 25 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Java try...finally block
We can also use the try block along with a finally block.
In this case, the finally block is always executed whether there is an
exception inside the try block or not
1 class Main {
2 public static void main ( String [] args ) {
3 try {
4 int divideByZero = 5 / 0;
5 }
6
7 finally {
8 System . out . println ( " Finally block is always executed " )
;
9 }
10 }
11 }
./code/FinallyBlock.java
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 26 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Flowchart of finally block
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 27 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Example of try catch with finally
1 class T e s t F i n a l l y B l o c k {
2 public static void main ( String args []) {
3 try {
4 // below code do not throw any exception
5 int data =25/5;
6 System . out . println ( data ) ;
7 }
8 // catch won ’t be executed
9 catch ( N u l l P o i n t e r E x c e p t i o n e ) {
10 System . out . println ( e ) ;
11 }
12 // executed regardless of exception occurred or not
13 finally {
14 System . out . println ( " finally block is always executed " ) ;
15 }
16
17 System . out . println ( " rest of phe code ... " ) ;
18 }
19 }
./code/TestFinallyBlock.java
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 28 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Flowchart of Multi-catch Block
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 29 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Java Multi-catch Block
1 public class M u l t i p l e C a t c h B l o c k 1 {
2 public static void main ( String [] args ) {
3 try {
4 int a []= new int [5];
5 a [5]=30/0; }
6 catch ( A r i t h m e t i c E x c e p t i o n e )
7 {
8 System . out . println ( " Arithmetic Exception
occurs " ) ;
9 }
10 catch ( A r r a y I n d e x O u t O f B o u n d s E x c e p t i o n e )
11 {
12 System . out . println ( " A r r a y I n d e x O u t O f B o u n d s
Exception occurs " ) ;
13 }
14 catch ( Exception e )
15 {
16 System . out . println ( " Parent Exception
occurs " ) ;
17 }
18 System . out . println ( " rest of the code " ) ;
19 }
20 } Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 30 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Handle Multiple Exceptions in a catch Block
In Java we can now catch more than one type of exception in a
single catch block
Each exception type that can be handled by the catch block is sepa-
rated using a vertical bar or pipe |.
Syntax of Multi-catch block
1 try {
2 // code
3 } catch ( E xcepti onType 1 | Exce ptiont ype2 ex ) {
4 // catch block
5 }
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 31 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Example : Multi-catch block
1 class Main {
2 public static void main ( String [] args ) {
3 try {
4 int array [] = new int [10];
5 array [10] = 30 / 0;
6 } catch ( A r i t h m e t i c E x c e p t i o n |
ArrayIndexOutOfBoundsException e) {
7 System . out . println ( e . getMessage () ) ;
8 }
9 }
10 }
./code/Multi_Catch_Block.java
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 32 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Catching base Exception
When catching multiple exceptions in a single catch block, the
rule is generalized to specialized.
This means that if there is a hierarchy of exceptions in the catch
block, we can catch the base exception only instead of catching
multiple specialized exceptions.
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 33 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Example: Catching base exception class
only
1 class Main {
2 public static void main ( String [] args ) {
3 try {
4 int array [] = new int [10];
5 array [10] = 30 / 0;
6 } catch ( Exception e ) {
7 System . out . println ( e . getMessage () ) ;
8 }
9 }
10 }
./code/CatchBaseException.java
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 34 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Example: Catching base and child exception
classes
If the base exception class has already been specified in the
catch block, do not use child exception classes in the same
catch block. Otherwise, we will get a compilation error.
1 class Main {
2 public static void main ( String [] args ) {
3 try {
4 int array [] = new int [10];
5 array [10] = 30 / 0;
6 } catch ( Exception | A r i t h m e t i c E x c e p t i o n |
ArrayIndexOutOfBoundsException e) {
7 System . out . println ( e . getMessage () ) ;
8 }
9 }
10 }
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 35 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Throw keyword in java
The throw keyword in Java is used to explicitly throw an excep-
tion from a method or any block of code. We can throw either
checked or unchecked exception. The throw keyword is mainly
used to throw custom exceptions.
The flow of execution of the program stops immediately after the
throw statement is executed and the nearest enclosing try block
is checked to see if it has a catch statement that matches the
type of exception
If it finds a match, controlled is transferred to that statement
otherwise next enclosing try block is checked and so on.
If no matching catch is found then the default exception handler
will halt the program.
1 \\ syntax of throw
2 throw th ro w ab l eO bj e ct ;
3 example :
4 throw new A r i t h m e t i c E x c e p t i o n ( " / by zero " ) ;
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 36 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Example: Use of throw keyword
1 class ThrowExcep
2 {
3 static void fun ()
4 {
5 try {
6 throw new N u l l P o i n t e r E x c e p t i o n ( " demo " ) ;}
7 catch ( N u l l P o i n t e r E x c e p t i o n e ) {
8 System . out . println ( " Caught inside fun () . " ) ;
9 throw e ; // rethrowing the exception
10 }
11 }
12 public static void main ( String args [])
13 {
14 try {
15 fun () ; }
16 catch ( N u l l P o i n t e r E x c e p t i o n e )
17 {
18 System . out . println ( " Caught in main . " ) ; }
19 }
20 }
./code/ThrowExcep.java
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 37 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Java throws keyword
We use the throws keyword in the method declaration to declare the
type of exceptions that might occur within it.
The caller to these methods has to handle the exception using a try-
catch block.
1 acce ssModi fier returnType methodName () throws ExceptionType1
, Except ionTyp e2 . . .{
2 // code
3 }
4
As you can see from the above syntax, we can use throws to declare
multiple exceptions.
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 38 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Example: Java Throws keyword
1 import java . io .*;
2 class Main {
3 public static void findFile () throws IOException {
4 // code that may produce IOException
5 File newFile = new File ( " test . txt " ) ;
6 F il eI n pu t St re a m stream = new F il eI n pu tS t re am ( newFile ) ;
7 }
8
9 public static void main ( String [] args ) {
10 try {
11 findFile () ;
12 } catch ( IOException e ) {
13 System . out . println ( e ) ;
14 }
15 }
16 }
./code/ThrowsExample1.java
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 39 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Example: Java Throws keyword
When we run this program, if the file test.txt does not exist,
FileInputStream throws a FileNotFoundException which extends
the IOException class.
The findFile() method specifies that an IOException can be
thrown. The main() method calls this method and handles the
exception if it is thrown
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 40 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Throwing multiple exceptions
1 import java . io .*;
2 class Main {
3 public static void findFile () throws NullPointerException ,
IOException , I n v a l i d C l a s s E x c e p t i o n {
4
5 // code that may produce N u l l P o i n t e r E x c e p t i o n
6
7 // code that may produce IOException
8
9 // code that may produce I n v a l i d C l a s s E x c e p t i o n
10 }
11 public static void main ( String [] args ) {
12 try {
13 findFile () ;
14 } catch ( IOException e1 ) {
15 System . out . println ( e1 . getMessage () ) ;
16 } catch ( I n v a l i d C l a s s E x c e p t i o n e2 ) {
17 System . out . println ( e2 . getMessage () ) ;
18 }
19 }
20 }
./code/JavaMultipleExceptions.java
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 41 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Throws keyword Vs. try . . . catch ... finally
There might be several methods that can cause exceptions.
Writing try...catch for each method will be tedious and code
becomes long and less-readable.
throws is also useful when you have checked exception (an
exception that must be handled) that you don’t want to catch in
your current method.
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 42 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Java User-defined exception (Custom excep-
tion)
In Java, we can create our own exceptions that are derived
classes of the Exception class.
Creating our own Exception is known as custom exception or
user-defined exception.
Why use custom exceptions?
To catch and provide specific treatment to a subset of existing
Java exceptions.
Business logic exceptions: These are the exceptions related
to business logic and workflow. It is useful for the application
users or the developers to understand the exact problem.
In order to create a custom exception, we need to extend the
Exception class that belongs to java.lang package
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 43 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Example: User-defined Exception
1 class MyException extends Exception {
2 public MyException ( String s )
3 { // Call constructor of parent Exception
4 super ( s ) ; }
5 }
6
7 // A Class that uses above MyException
8 public class Main {
9 public static void main ( String args [])
10 {
11 try {
12 // Throw an object of user defined exception
13 throw new MyException ( " CSE2005 " ) ; }
14 catch ( MyException ex ) {
15 System . out . println ( " Caught " ) ;
16 // Print the message from MyException object
17 System . out . println ( ex . getMessage () ) ;
18 }
19 }
20 }
./code/UserDefinedExecption1.java
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 44 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Java garbage Collection
In java, garbage means un-referenced Objects Garbage Collec-
tion is process of reclaiming the runtime unused memory automati-
cally. In other words, it is a way to destroy the unused objects
Advantage of Garbage Collection
It makes java memory efficient because garbage collector
removes the unreferenced objects from heap memory.
It is automatically done by the garbage collector(a part of JVM)
so we don’t need to make extra efforts.
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 45 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
How can an Object be unreferenced ?
There are many ways like:
By nulling the reference
By assigning a reference to another
By anonymous object etc.
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 46 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
1. By nulling a reference:
1 Employee e = new Employee () ;
2 e = null ;
2. By assigning a reference to another:
1 Employee e1 = new Employee () ;
2 Employee e2 = new Employee () ;
3 e1 = e2 ; // now the first object referred by e1 is available for
garbage collection
3) By anonymous object:
1 new Employee () ;
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 47 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
finalize() method
The finalize() method is invoked each time before the object is
garbage collected.
This method can be used to perform cleanup processing.
This method is defined in Object class as:
1 protected void finalize () {};
2
Note: The Garbage collector of JVM collects only those objects that
are created by new keyword. So if you have created any object with-
out new, you can use finalize method to perform cleanup processing
(destroying remaining objects).
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 48 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
gc() method
The gc() method is used to invoke the garbage collector to per-
form cleanup processing.
The gc() is found in System and Runtime classes.
1 public static void gc () {};
Note: Garbage collection is performed by a daemon thread called
Garbage Collector(GC). This thread calls the finalize() method before
object is garbage collected.
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 49 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Example of garbage collection in Java
1 public class TestGarbage1 {
2 public void finalize () { System . out . println ( " object is
garbage collected " ) ;}
3 public static void main ( String args []) {
4 TestGarbage1 s1 = new TestGarbage1 () ;
5 TestGarbage1 s2 = new TestGarbage1 () ;
6 s1 = null ;
7 s2 = null ;
8 System . gc () ;
9 }
10 }
./code/GarbageExample.java
Note: Neither finalization nor garbage collection is guaranteed.
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 50 / 51
java Exceptions Java Exception Hierarchy Types of Exception in Java Java Exception Handling Java try...catch Java Nested try block Java try...finally blo
Dr. Nikhil Mhala
Contact:
[email protected]
Landline: 0863-2370961 (Mon-Fri 9 am - 5 pm)
Extension: 5961
Dr. Nikhil Mhala VIT-AP CSE2005 May 15, 2022 51 / 51