21CS203 / Object Oriented Programming 2025
UNIT-II
EXCEPTION HANDLING AND STRINGS
EXCEPTIONS
What is exception handling in Java?
When an error occurs, Java will normally stop and generate an error message.
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running
out of memory, memory leaks, stack overflow errors, library incompatibility, infinite
recursion, etc.
Major reasons why an error occurs
o Invalid user input
o Device failure
o Loss of network connection
o Physical limitations (out of disk memory)
o Code errors
o Opening an unavailable file
Errors are usually beyond the control of the programmer, and we should not try to handle
errors.
Exception is an abnormal condition raised by the application / coding itself.
Exception handling is the process of responding to unwanted or unexpected events when a
code / program is executed.
Exception handling deals with these events to avoid the program or system crashing, and
without this process, exceptions would disrupt the normal operation of a program.
An exception is an object that can be thrown at runtime.
Exception Handling is a mechanism to handle runtime errors such as
o ClassNotFoundException,
o IOException,
o SQLException,
o RemoteException, etc.
Dr. A.M.Rajeswari, CSE, VCET Page 1 of 20
21CS203 / Object Oriented Programming 2025
Difference between errors and exceptions in Java
Errors and exceptions are subclasses of the Throwable Java class.
The Error class represents critical conditions that cannot be caught and handled by the
code of the program.
On the other hand, the Exception class represents concerning conditions raised by the
application itself; these can be caught and handled within the code to ensure that the
application continues to run smoothly.
Dr. A.M.Rajeswari, CSE, VCET Page 2 of 20
21CS203 / Object Oriented Programming 2025
The key differences between exceptions and errors are as follows:
Errors Exceptions
Errors are usually raised by the Exceptions are caused by the code of the
environment in which the application is application itself.
running. For example, an error will occur due
to a lack of system resources.
It is not possible to recover from an error ie., The use of try-catch blocks can handle
not able to handle. exceptions and recover the application from
them.
Errors occur at run-time and are not known Exceptions can be “checked” or
by the compiler; hence, they are classified as “unchecked,” meaning they may or may not
“unchecked.” be caught by the compiler.
“OutOfMemory” and “StackOverflow” are Unchecked exception: “IndexOutOfBounds”
examples of errors. Checked exception : “ClassNotFound”
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.
Let's consider a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8; This portion will not be executed
9. statement 9;
10. statement 10;
When we perform exception handling, the rest of the statements (statement 6 … statement
10) will be executed.
Dr. A.M.Rajeswari, CSE, VCET Page 3 of 20
21CS203 / Object Oriented Programming 2025
Hierarchy of Java Exception
Types of Java Exception (Refer Text book for more examples and details)
According to Oracle Java, there are three types of exceptions namely:
1) Checked Exception
The classes that directly inherit the Throwable class (except RuntimeException and
Error) are known as checked exceptions.
o Example: IOException, SQLException, etc.
Checked exceptions are checked at compile-time.
Dr. A.M.Rajeswari, CSE, VCET Page 4 of 20
21CS203 / Object Oriented Programming 2025
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions.
o Example: ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc.
Unchecked exceptions are not checked at compile-time, but they are checked at
runtime.
3) Error
Error is irrecoverable.
o Example of errors: OutOfMemoryError, VirtualMachineError, AssertionError etc.
(Assertions are used for debugging and validating assumptions about the internal
state of a program during development)
How Does JVM Handle an Exception?
(Refer: https://www.geeksforgeeks.org/exceptions-in-java/)
Dr. A.M.Rajeswari, CSE, VCET Page 5 of 20
21CS203 / Object Oriented Programming 2025
Example:
1. // Class ThrowsExecp
2. class GFG
3. {
4. // Main driver method
5. public static void main(String args[])
6. {
7. String str = null; // Taking an empty string
8. System.out.println(str.length()); // Getting length of a string
9. }
10. }
Output
How Programmer Handle an Exception?
Customized Exception Handling: Java exception handling is managed via five keywords:
- TRY, CATCH, THROW, THROWS, and FINALLY.
Dr. A.M.Rajeswari, CSE, VCET Page 6 of 20
21CS203 / Object Oriented Programming 2025
Java Exception Handling Example
1. public class JavaExceptionExample 1. public class JavaExceptionExample
2. { 2. {
3. public static void main(String args[]) 3. public static void main(String args[])
4. { 4. {
5. int data=100/0; 5. Try //code that may raise exception
6. System.out.println("rest of the code..."); 6. { int data=100/0; }
7. } 7. Catch (ArithmeticException e)
8. } 8. { System.out.println(e); }
9. System.out.println("rest of the code...");
10. }
11. }
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
Keyword Description
try The "try" keyword is used to specify a block where we should place the
code which has to be tested for errors.
We can't use try block alone, it must be followed by either catch or finally
blocks.
catch The "catch" block is used to handle the exception if an error occurs in the
Dr. A.M.Rajeswari, CSE, VCET Page 7 of 20
21CS203 / Object Oriented Programming 2025
try block.
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
regardless of whether the exception has occurred or handled.
throw The "throw" keyword is used to throw an exception. It allows you to create a
custom errors.
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.
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.
Flowchart of Multi-catch Block
Dr. A.M.Rajeswari, CSE, VCET Page 8 of 20
21CS203 / Object Oriented Programming 2025
Example:
1. public class MultipleCatchBlock1
2. {
3. public static void main(String[] args)
4. {
5. Try
6. {
7. int arr1[]=new int[5];
8. a[5]=30/0; // 1. Divide by zero & 2. Array out of bound
9. }
10. catch(ArithmeticException e) // Catch1
11. { System.out.println("Arithmetic Exception occured"); }
12. catch(ArrayIndexOutOfBoundsException e) // Catch2
13. { System.out.println("ArrayIndexOutOfBounds Exception occured"); }
14. catch(Exception e) // Catch3
15. { System.out.println("Parent Exception occured"); }
16. System.out.println("rest of the code");
17. }
18. }
Output:SA Announces New Milestone in Mystery of Universe's Expansion Rate
Arithmetic Exception occurs
rest of the code
Java 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. public class NestedTryBlock
2. {
3. public static void main(String args[])
Dr. A.M.Rajeswari, CSE, VCET Page 9 of 20
21CS203 / Object Oriented Programming 2025
4. {
5. //outer try block
6. Try
7. {
//inner try block 1
8. Try
9. {
10. System.out.println("going to divide by 0");
11. int b =39/0;
12. }
13. //catch block of inner try block 1
14. catch(ArithmeticException e)
15. { System.out.println(e); }
16. //inner try block 2
17. Try
18. {
19. int a[]=new int[5];
20. //assigning the value out of array bounds
21. a[5]=4;
22. }
23. //catch block of inner try block 2
24. catch(ArrayIndexOutOfBoundsException e)
25. { System.out.println(e); }
26. System.out.println("other statement");
27. } //end of the outer try block
28. //catch block of outer try block
29. catch(Exception e)
30. { System.out.println("handled the exception (outer catch)"); }
31. System.out.println("normal flow..");
32. } //end of the class
Output:
Dr. A.M.Rajeswari, CSE, VCET Page 10 of 20
21CS203 / Object Oriented Programming 2025
Java 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 occur or not.
The finally block follows the try-catch 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.
Flowchart of finally block
Dr. A.M.Rajeswari, CSE, VCET Page 11 of 20
21CS203 / Object Oriented Programming 2025
Usage of Java finally
1. When an exception does not occur.
2. When an exception occur but not handled by the catch block (when no relevant catch
available)
3. When an exception occurs and is handled by the catch block.
Example:
1. class TestFinallyBlock
2. {
3. public static void main(String args[])
4. {
5. Try
6. {
7. //below code do not throw any exception
8. int data=25/5;
9. System.out.println(data);
10. }
11. //catch won't be executed
12. catch(NullPointerException e)
13. { System.out.println(e); }
14. //executed regardless of exception occurred or not
15. finally
16. { System.out.println("finally block is always executed"); }
17. System.out.println("rest of the code...");
18. } //end of main method
19. } //end of class
Output:
Dr. A.M.Rajeswari, CSE, VCET Page 12 of 20
21CS203 / Object Oriented Programming 2025
Difference between final, finally and finalize.
S.no Key final finally finalize
1. Definition final is the keyword finally is the block in finalize is the method
and access modifier Java Exception in Java which is used
which is used to apply Handling to execute the to perform clean up
restrictions on a class, important code whether processing just before
method or variable. the exception occurs or object is garbage
not. collected.
2. Applicable Final keyword is used Finally block is always finalize() method is
to with the classes, related to the try and used with the objects.
methods and catch block in exception
variables. handling.
3. Functionality (1) Once declared, (1) finally block runs finalize method
final variable becomes the important code even performs the cleaning
constant and cannot be if exception occurs or activities with respect
modified. not. to the object before its
(2) final method (2) finally block cleans destruction.
cannot be overridden up all the resources
by sub class. used in try block
(3) final class cannot
be inherited.
4. Execution Final method is Finally block is finalize method is
executed only when executed as soon as executed just
we call it. the try-catch block before the object is
is executed. destroyed.
It's execution is not Can be called
dependant on the explicitily
exception.
Example: Final
1. public class FinalExampleTest
2. {
3. final int age = 18; //declaring final variable
4. void display()
5. {
6. age = 55; // reassigning value to age variable, gives compile time error
7. }
8. public static void main(String[] args)
9. {
Dr. A.M.Rajeswari, CSE, VCET Page 13 of 20
21CS203 / Object Oriented Programming 2025
10. FinalExampleTest obj = new FinalExampleTest();
11. obj.display(); // gives compile time error
12. }
13. }
Output:
Finalize method
It is a method that the Garbage Collector always calls just before the deletion/destroying
of the object which is eligible for Garbage Collection, so as to perform clean-up activity.
Clean-up activity means closing the resources associated with that object like Database
Connection, Network Connection, or we can say resource de-allocation.
Remember, it is not a reserved keyword. Once the finalized method completes immediately
Garbage Collector destroys that object.
Since the Object class contains the finalize method, finalize method is available for every
Java class since Object is the superclass of all Java classes.
Finalize method can also be overridden.
Example: Finalize
1. class Bye
2. {
3. public static void main(String[] args)
4. {
5. Bye m = new Bye();
6. m.finalize(); // Calling finalize method Explicitly.
7. m.finalize();
8. m = null;
9. System.gc(); // Requesting JVM to call Garbage Collector method
10. System.out.println ("Main Completes");
11. }
Dr. A.M.Rajeswari, CSE, VCET Page 14 of 20
21CS203 / Object Oriented Programming 2025
12. public void finalize() // Here overriding finalize method
13. { System.out.println( "finalize method overridden" ); }
14. }
Output:
finalize method overridden //call by programmer, object won't gets destroyed.
finalize method overridden //call by programmer, object won't gets destroyed.
Main Completes
finalize method overridden
//call by Garbage Collector just before destroying the object.
Difference between throw and throws in Java
The throw and throws is the concept of exception handling where the throw keyword
throw the exception explicitly from a method or a block of code.
The throws keyword is used in signature of the method.
There are many differences between throw and throws keywords. A list of differences
between throw and throws are given below:
S.no. Basis of throw throws
Differences
1. Definition Java throw keyword is used to Java throws keyword is used in
throw an exception explicitly the method signature to declare
in the code, inside the function an exception which might be
or the block of code. thrown by the function while the
execution of the code.
2. Usage Type of exception Using throw Using throws keyword, we can
keyword, we can only declare both checked and
propagate unchecked unchecked exceptions. However,
exception i.e., the checked the throws keyword can be
exception cannot be propagated used to propagate checked
using throw only. exceptions only.
3. Syntax The throw keyword is The throws keyword is followed
followed by an instance of by class names of Exceptions to
Exception to be thrown. be thrown.
Dr. A.M.Rajeswari, CSE, VCET Page 15 of 20
21CS203 / Object Oriented Programming 2025
4. Declaration Throw is used within the Throws is used with the method
method. signature.
5. Internal We are allowed to throw only We can declare multiple
implementation one exception at a time i.e. we exceptions using throws
cannot throw multiple keyword that can be thrown by
exceptions. the method. For example, main()
throws IOException,
SQLException.
Example:
1. public class TestThrowAndThrows
2. { // defining a user-defined method which throws ArithmeticException
3. static void method() throws ArithmeticException // throws in method declaration
4. {
5. System.out.println("Inside the method()");
6. throw new ArithmeticException("throwing ArithmeticException");
// throw for throwing exception
7. }
8. public static void main(String args[]) //main method
9. {
10. try { method(); } //calling static method without object
11. catch(ArithmeticException e)
12. { System.out.println("caught in main() method"); }
13. }
14. }
Output:
Dr. A.M.Rajeswari, CSE, VCET Page 16 of 20
21CS203 / Object Oriented Programming 2025
Java Stack Trace
In Java, stack trace is nothing but location of the exceptions.
In Java, the stack trace is an array of stack frames.
It is also known as stack backtrace (or backtrace).
The stack frames represent the movement of an application during the execution of the
program. It traces the locations where exception raised.
The „StackTraceElement’ class provides a constructor that parses four parameters as
an argument and creates a stack trace element that denotes the specified execution point.
public StackTraceElement
(String declaringClass, String methodName, String fileName, int lineNumber)
Parameters:
1. declaringClass: the qualified name of the class that contains the execution point.
2. methodName: It represents the method name that contains the execution point.
3. fileName: It represents the file name that contains the execution point.
4. lineNumber: It represents the line number of the source of the execution point.
Textual representation (Syntax) of StackRace
Exception in thread "main" java.lang.NullPointerException: Fictitious NullPointerExce
ption
at ClassName.methodName1(ClassName.java:lineNumber)
Dr. A.M.Rajeswari, CSE, VCET Page 17 of 20
21CS203 / Object Oriented Programming 2025
at ClassName.methodName2(ClassName.java:lineNumber)
at ClassName.methodName3(ClassName.java:lineNumber)
at ClassName.main(ClassName.java:lineNumber)
The first line denotes:
The other line(s) denotes:
Example:
1. public class StackTraceExample
2. {
3. public static void main(String args[])
4. {
5. demo();
6. }
7. static void demo()
8. {
9. demo1();
10. }
Dr. A.M.Rajeswari, CSE, VCET Page 18 of 20
21CS203 / Object Oriented Programming 2025
11. static void demo1()
12. {
13. demo2();
14. }
15. static void demo2()
16. {
17. demo3();
18. }
19. static void demo3()
20. {
21. Thread.dumpStack();
22. }
23. }
Let's run the above program and see the stack trace.
The Java Thread dumpStack() method prints a stack trace of the current thread to the
standard error stream. This method is used only for debugging.
Reference:
https://www.javatpoint.com/exception-handling-in-java
https://www.geeksforgeeks.org/exceptions-in-java/
https://www.geeksforgeeks.org/exceptions-in-java/
https://www.javatpoint.com/difference-between-throw-and-throws-in-java
https://www.geeksforgeeks.org/g-fact-24-finalfinally-and-finalize-in-java/
https://www.javatpoint.com/difference-between-final-finally-and-finalize
Dr. A.M.Rajeswari, CSE, VCET Page 19 of 20
21CS203 / Object Oriented Programming 2025
******************
Dr. A.M.Rajeswari, CSE, VCET Page 20 of 20