Exception Handling
Exception Handling
Exception Handling
Learning Level :
DATE : 26.09.2024
Exception handling
Realtime Scenario
• Whenever we travel in Aircraft, Airhostess used to give demonstration of steps that the passengers
have to take in case of emergency.
Realtime Scenario
• The reason is that we have to be aware of how to handle a situation in case of any emergency while
you are flying.
• This scenario explains how you have to think in advance the many possibilities of mishaps that can
happen and the preventive measures to save.
• Similarly, when we write the programs as a part of any application, we have to visualize the challenges
that can disrupt the normal flow of execution. If so, how to overcome these.
• In Java, Exception handling mechanism helps the programmer to have a comfortable seat when such
situation occurs.
What is an Exception?
• An exception is an unexpected event, which occurs during the execution of a program i.e., at run time
that disrupts the normal flow of the program’s instructions.
- etc.
Example
class SimpleArithmetic {
public static void main(String args[]){
Output:
Exception Types
- Checked Exceptions
- Unchecked Exceptions
- Errors
Checked Exceptions
• It is an exception that occurs at the compile time, these are also called as compile-time exceptions.
• These exceptions cannot simply be ignored at the time of compilation, the programmer should take
- IOException
- ClassNotFound Exception
- SQLException
- SocketException,
- etc.,
Unchecked Exceptions
• An unchecked exception is an exception that occurs at the time of execution. These are also called
as Runtime Exceptions.
• These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions
- ArithmeticException
- NullPointerException,
- ArrayIndexOutOfBoundsException
- etc.,
Errors
• Errors are abnormal conditions that happen in case of severe failures, these are not handled by the
Java programs.
Examples:
- OutOfMemoryError
- VirtualMachineError
- StackOverflowError
- etc.,
• There are several built-in classes that are used to handle the fundamental errors that may occur in your
programs.
• Also, we can create our own exceptions based on the application needs by extending Exception
class.
Exception Hierarchy
Exception Hierarchy
• All exception and errors types are subclasses of class Throwable, which is the base class of the
hierarchy. There are three main types of Throwable:
Error
RuntimeException
Exception
• Recoverable error
Note:
• In Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under
throwable is checked.
15 Exception handling | ©SmartCliff | Internal | Version 1.0
Exception handling
In the above example, program will be terminated abruptly and the rest of codes will not get executed due to
exception
Note:
First two steps are taken care by Try block and rest of the steps taken care by Catch block.
• Whenever inside a method, if an exception has occurred, the method creates an Object known as
• The exception object contains name and description of the exception, and current state of the
• Creating the Exception Object and handling it to the run-time system is called throwing an Exception.
• There could be a list of methods that were called to obtain the method in which the exception took place.
• The run-time system searches the call stack to find the method that contains block of code that can
handle the occurred exception. The block of the code is called Exception handler.
• The run-time system starts searching from the method in which exception occurred, proceeds through
• If it finds appropriate handler (the type of the exception object thrown matches the type of the
exception object it can handle) then it passes the occurred exception to it.
• If couldn’t have found the appropriate handler then run-time system handover the Exception Object
to default exception handler , which is part of run-time system. This handler prints the exception
information and terminates program abnormally.
19 Exception handling | ©SmartCliff | Internal | Version 1.0
Exception handling
Keyword Description
Try-catch block
try{
….
-- code which may cause an exception
….
}
catch(ExceptionType e){
…
-- Code to handle the exception
…
}
e.printStackTrace();
• toString() method :we can print only name and description of an exception
System.out.println(e.getMessage());
• You can specify two or more catch clauses, each can catch different type of exception
• When an exception is thrown, each catch statement is inspected in order, and the first one whose
• After one catch statement executes, the others are bypassed, and execution continues after the
try/catch block
try {
catch(ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}
catch(Exception e) {
System.out.println(e);
}
System.out.println("rest of the code...");
}
}
throw keyword
• The throw keyword in Java is used to explicitly throw an exception from a method or any block of code.
Syntax:
throw exception;
throws keyword
• throws is a keyword in Java which is used in the signature of method to indicate that this method might
• The caller to these methods has to handle the exception using a try-catch block.
• To handle the exception when you call this method, all the exceptions that are declared using throws,
must be handled where you are calling this method else you will get a compilation error.
Syntax:
type method_name(parameters) throws exception_list
finally block
• finally block is a block that is used to execute important code such as closing connection, stream etc.
Note: If you don't handle exception, before terminating the program, JVM executes finally block(if any).
• But there may be cases where we may have to define our own exceptions which are application specific
• While creating user defined exceptions, the following aspects have to be taken care :
- The user defined exception class should extend from the Exception class and its Subclass.
- If we want to display meaningful information about the exception, we should override the toString()
method
Assertions
• It is used for testing the correctness of any assumptions that have been made in the program.
• When the program is running with assertions enabled, the condition is checked at runtime. If the
condition is false, the Java runtime system throws an AssertionError.
Syntax:
Assertions
Enabling Assertions
Disabling Assertions
Assertions: Example #1
Assertions: Example #2
Assertions: Example #3
// Java program to demonstrate syntax of assertion
import java.util.Scanner;
class AssertionDemo{
public void Test(int a){
assert a>=18:" You are not Eligble for Vote";
System.out.println("Your age: "+a);
}
public static void main( String args[] ) {
AssertionDemo obj=new AssertionDemo();
Scanner scanner = new Scanner( System.in );
System.out.print("Enter your age ");
int value = scanner.nextInt();
obj.Test(value);
}
}
54 Exception handling | ©SmartCliff | Internal | Version 1.0
Exception handling
Assertions
• Conditional cases.
Quiz
a) Class b) Interface
a) Class
Quiz
a) java.lang b) java.util
c) java.io d) java.awt.
a) java.lang
Quiz
Quiz
a) catch{ } b) finally{ }
c) try{ }
d) try{ }.
catch(Exception e){ }
finally{ }
c) try{ }
catch(Exception e){ }
finally{ }
Quiz