Oop L21
Oop L21
Exception Handling
• Exception Handling in Java is one of the effective means to handle runtime errors so
that the regular flow of the application can be preserved.
• What is Exception? In Java, Exception is an unwanted or 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.
• When an exception occurs within a method, it creates an object. This object is called
the exception object.
• It contains information about the exception, such as the name and description of the
exception and the state of the program when the exception occurred.
• Exceptions can be caught and handled by the program.
• 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:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9; With appropriate exception handling, the
statement 10; statements from 6-10 will be executed.
• 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
Hierarchy of Java Exception classes
The java.lang.Throwable class is the root class of Java Exception hierarchy
inherited by two subclasses: Exception and Error.
• 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.
• Example of Checked Exception:
import java.io.*;
class GFG {
public static void main(String[] args)
{
FileReader file = new FileReader("C:\\test\\a.txt");
BufferedReader fileInput = new BufferedReader(file);