Exception Handling, hierarchy
Exception types and methods
Concepts of “ try, catch and throw and finally” in exceptions
Exception Handling, hierarchy
Exception types and methods
Concepts of “ try, catch and throw and finally” in exceptions
Exception handling is the practice of addressing unforeseen or abnormal occurrences that can arise during the execution of a computer program. This approach is crucial for managing these incidents to prevent the program or system from experiencing a breakdown, as without this mechanism, anomalies would interrupt the program's typical functioning
Exception handling in Java is a system for managing unexpected disruptions, such as exceptions, so that the program can proceed with its regular execution.
In Java, you employ constructs like try-catch blocks along with keywords such as finally, throw, and throws to manage exceptions.
When an exception arises, the Java Virtual Machine (JVM) naturally takes care of it.
In such cases, the program's execution comes to a stop, and the raised exception is reported.
The primary benefit of exception handling is to ensure the smooth and uninterrupted operation of an application. Exceptions typically introduce disruptions in the regular flow of an application, which is why it's essential to address them.
Let's examine a scenario..
statement 1;
statement 2;
statement 3;
statement 4; //exception occurs
statement 5;
statement 6;
statement 7;
Suppose there are 7 statements in a Java program and an exception occurs at statement 4; the rest of the code will not be executed,
However, when we perform exception handling, the rest of the statements will be executed. That is why we use exception handling in Java.
The foundation of the Java Exception hierarchy lies in the java.lang.Throwable class, which serves as the parent class inherited by two main subclasses: Exception and Error. This hierarchy of Java Exception classes is outlined as follows
There are mainly two types of exceptions: checked and unchecked. An error is considered as the unchecked exception. However, according to Oracle, there are three types of exceptions namely:
Checked Exception
Unchecked Exception
Error
Checked and unchecked exceptions are a classification of exceptions in programming, particularly in languages like Java.
Here's a table summarizing the main differences between checked and unchecked exceptions:
Checked Exceptions:
Must be declared using the throws keyword or handled with a try-catch block.
Typically used for situations where the program can reasonably anticipate and recover from the exception, such as file I/O or database operations.
Encourage better error handling practices and make it clear when a method may throw exceptions.
Extends the java.lang.Exception class.
Unchecked Exceptions:
Do not need to be declared or explicitly handled, although they can be handled if desired.
Usually related to programming errors or unexpected runtime conditions, like null references or array out-of-bounds access.
Tend to indicate bugs in the code or issues that are not easily recoverable.
Extend the java.lang.RuntimeException class.
Error
Errors are situations in programming that cannot be recovered from. Examples of such errors include OutOfMemoryError, VirtualMachineError, and AssertionError
Here's a table summarizing the main Java keywords and their purposes when dealing with exceptions:
In Java, exceptions are a way to handle unexpected situations or errors that can occur during program execution. Java provides a variety of exception keywords and classes to help you handle different types of exceptions. Here are some common exception keywords and examples:
1.try: The try block is used to enclose the code that might throw an exception.
If an exception occurs within the try block, it can be caught and handled by the corresponding catch block.
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Handle the exception
}
2.catch: The catch block follows a try block and is used to catch and handle exceptions. You specify the exception type you want to catch in parentheses.
try {
int result = 10 / 0; // This will throw an ArithmeticException
} catch (ArithmeticException e) {
System.out.println("An arithmetic exception occurred: " + e.getMessage());
}
3.finally: The finally block is used to specify code that should be executed regardless of whether an exception was thrown or not. It's often used for cleanup operations.
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Handle the exception
} finally {
// Cleanup code
}
4.throw: The throw keyword is used to explicitly throw an exception. You can throw any exception that's a subclass of Throwable.
void checkAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
}
5.throws: The throws keyword is used in method declarations to indicate that a method might throw a particular type of exception. It is used to declare exceptions that the method does not handle but propagates to the caller.
void readFile() throws IOException {
// Code that might throw an IOException
}
Exception Types: Java has a hierarchy of exception types. Some common exception types include:
ArithmeticException: Thrown when an arithmetic operation results in an error, such as division by zero.
NullPointerException: Thrown when an attempt is made to access an object or call a method on a null reference.
ArrayIndexOutOfBoundsException: Thrown when an attempt is made to access an array element with an illegal index.
FileNotFoundException: Thrown when a specified file cannot be found.
IOException: A general exception for I/O-related errors.
NumberFormatException: Thrown when an invalid conversion from a string to a numeric type is attempted.
Here's a simple example demonstrating some of these concepts:
public class ExceptionExample {\
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw an ArithmeticException
} catch (ArithmeticException e) {
System.out.println("An arithmetic exception occurred: " + e.getMessage());
} finally {
System.out.println("This block always executes.");
}
}
}
In this example, we catch an ArithmeticException, print a message, and then execute the finally block.
Exception Handling Example :-
import java.util.Scanner;
public class ExceptionHandlingExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numerator, denominator, result;
try {
System.out.print("Enter the numerator: ");
numerator = scanner.nextInt();
System.out.print("Enter the denominator: ");
denominator = scanner.nextInt();
result = divide(numerator, denominator);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.err.println("Error: Division by zero is not allowed.");
} catch (java.util.InputMismatchException e) {
System.err.println("Error: Please enter valid integers.");
} finally {
// Close the scanner in the finally block to ensure it's always closed.
scanner.close();
}
}
public static int divide(int numerator, int denominator) {
return numerator / denominator;
}
}
The provided Java program demonstrates exception handling for division by zero and invalid input using a try, catch, and finally block. When you run this program and provide input, here's the expected output for various scenarios:
Scenario 1: Valid Input
Enter the numerator: 10
Enter the denominator: 2
Result: 5
In this case, valid input is provided, and the division operation (numerator / denominator) is successful, resulting in the expected result of 5.
Scenario 2: Division by Zero
Enter the numerator: 5
Enter the denominator: 0
Error: Division by zero is not allowed
Here, an attempt to divide by zero is made, resulting in an ArithmeticException. The program catches this exception and displays an error message.
Scenario 3: Invalid Input
Enter the numerator: abc
Error: Please enter valid integers
In this case, invalid input (non-integer characters) is provided when entering the numerator.
The InputMismatchException is caught, and the program displays an error message.
Please note that the program also closes the Scanner object in the finally block to ensure proper resource cleanup, regardless of whether an exception occurs or not.