Exception and Exception Handling
In Java, an exception is an event that disrupts the normal flow of a program's instructions during its execution. Exceptions can occur due to various reasons such as incorrect input, division by zero, or attempting to access an array element outside its bounds. Exception handling in Java allows you to gracefully deal with these unexpected events, preventing program crashes and providing a way to handle errors effectively.
Types of Exceptions:
Checked Exceptions: Checked exceptions in Java are exceptions that are checked at compile time. This means that the Java compiler ensures that these exceptions are either caught or declared in the method signature using the
throws
keyword. Checked exceptions are typically used for conditions that are outside the control of the program, such as file I/O errors or network connectivity issues.Unchecked Exceptions (Runtime Exceptions): Unchecked exceptions, also known as runtime exceptions, are exceptions that are not checked at compile time. Unlike checked exceptions, which the compiler forces you to handle, unchecked exceptions can occur at runtime and are not required to be caught or declared in the method signature. Unchecked exceptions are typically caused by programming errors, such as accessing an array index out of bounds or attempting to divide by zero.
Exception Handling in Java:
Java provides keywords try
, catch
, finally
, and throw
to handle exceptions.
try
: Thetry
block contains the code that might throw an exception.catch
: Thecatch
block catches and handles the exception thrown in thetry
block.finally
: Thefinally
block contains code that will be executed regardless of whether an exception occurs or not.throw
: Thethrow
keyword is used to throw a specific exception explicitly.
Example Code:
Explanation:
The program attempts to read an integer from the user.
If the user enters a non-integer value, it catches
InputMismatchException
and prints an error message.If the user enters 0 (for division), it catches
ArithmeticException
and prints an error message.The
finally
block always executes, allowing you to close resources or execute essential cleanup code.Regardless of exceptions, the program continues to execute after the
try-catch
blocks.
When you run this Java program:
If you enter a non-integer value, it will catch
InputMismatchException
.If you enter 0, it will catch
ArithmeticException
.In either case, the program will execute the
finally
block before termination.
This example demonstrates how to handle exceptions in Java and how the try
, catch
, and finally
blocks work together to ensure the program doesn't crash unexpectedly.
How to Handle Checked Exceptions:
Catching Checked Exceptions: You can catch checked exceptions using
try
andcatch
blocks. If a method throws a checked exception, it must be either caught or declared in the method signature.Declaring Checked Exceptions: If a method may throw a checked exception, you should declare it in the method signature using the
throws
keyword. This informs the calling method that it needs to handle the exception.
Example Code with Checked Exception:
Explanation:
In this example, the FileReader
constructor may throw an IOException
if the specified file does not exist. The code inside the try
block attempts to create a FileReader
object for a file that might not be present.
The
try
block contains the code that might throw the checked exception (IOException
in this case).The
catch
block catches theIOException
and handles it by printing an error message.Since
IOException
is a checked exception, it must be caught or declared using thethrows
keyword in the method signature.
When you run this Java program, it will handle the IOException
gracefully without crashing, even if the file does not exist. This is an essential mechanism for building robust Java applications.
Common Unchecked Exceptions in Java:
ArithmeticException
: Thrown when an arithmetic operation (like division) has an exceptional condition.NullPointerException
: Thrown when trying to access an object that isnull
.ArrayIndexOutOfBoundsException
: Thrown when attempting to access an array element at an invalid index.NumberFormatException
: Thrown when trying to convert a string to a numeric type, but the string does not have the appropriate format.
Handling Unchecked Exceptions:
Unchecked exceptions are not required to be caught or declared. However, it's good practice to handle them if you anticipate them in your code to prevent unexpected program termination.
Example Code with Unchecked Exception:
Explanation:
In this example, the program deliberately creates scenarios where unchecked exceptions (ArithmeticException, NullPointerException, and ArrayIndexOutOfBoundsException) occur:
int result = 10 / 0;
: This line attempts to divide by zero, resulting in anArithmeticException
.int length = str.length();
:str
isnull
, so trying to access itslength()
method results in aNullPointerException
.int value = numbers[5];
:numbers
array does not have an element at index 5, leading to anArrayIndexOutOfBoundsException
.
Each scenario is caught in a try-catch
block, and an error message is printed. Handling these exceptions prevents the program from crashing unexpectedly, allowing it to continue executing the subsequent code.
Last updated