Exceptional Handling
Definition
Exceptional handling is the mechanism used in programming to detect, report, and manage runtime errors or abnormal conditions so that the normal flow of the program can continue or terminate safely.
In Java, exceptional handling is done using keywords such as try, catch, finally, throw, and throws. These constructs help programmers identify risky code, handle exceptions properly, and maintain program stability.
Main Content
1. Basics of Exception and Exception Types
Exception meaning and need
An exception is an event that disrupts the normal execution of a program. It may happen due to invalid input, missing files, division by zero, null object access, or resource failure. Without exception handling, such problems can cause program termination.
Example:
int a = 10 / 0;
This causes an ArithmeticException because division by zero is not allowed.
Types of exceptions in Java
Java exceptions are broadly categorized into:
- Checked exceptions: These are checked at compile time. The programmer must handle them using
try-catchor declare them usingthrows. Examples:IOException,FileNotFoundException. - Unchecked exceptions: These are checked at runtime. They usually occur due to programming mistakes. Examples:
NullPointerException,ArithmeticException,ArrayIndexOutOfBoundsException. - Errors: These are serious problems related to the Java Virtual Machine or system environment and are generally not handled by application code. Examples:
OutOfMemoryError,StackOverflowError.
ASCII view of the hierarchy:
Object
|
Throwable
|
+-- Exception
| |
| +-- Checked Exceptions
| +-- RuntimeException
|
+-- Error
2. Exception Handling Keywords
try block
The try block contains code that may generate an exception. It is the first step in protecting risky code. If an exception occurs inside try, the normal flow stops and control moves to the matching catch block.
Example:
try {
int result = 10 / 0;
}
catch block
The catch block handles the exception thrown by the try block. It allows the programmer to provide an error message, recover from the problem, or execute alternate logic.
Example:
catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
}
finally, throw, and throws
finallyexecutes whether an exception occurs or not. It is commonly used to close files, release database connections, or perform cleanup tasks.throwis used to explicitly create and throw an exception.throwsis used in method declarations to indicate that a method may pass an exception to the caller.
Example:
try {
// risky code
} catch (Exception e) {
System.out.println("Handled");
} finally {
System.out.println("Cleanup done");
}
3. Exception Handling Process and Best Practices
Flow of exception handling
When an exception occurs, Java creates an exception object and passes it to the runtime system. The system searches for a suitable catch block. If found, the exception is handled; otherwise, the program terminates and prints a stack trace.
What happens:
- Code inside
tryis executed. - If an exception occurs, control jumps to the matching
catch. finallyruns aftercatchor aftertryif no exception occurs.
Best practices for effective handling
- Catch specific exceptions rather than using a generic
Exceptioneverywhere. - Use
finallyor try-with-resources to close resources properly. - Avoid hiding errors silently.
- Provide meaningful error messages to help debugging.
- Use custom exceptions when application-specific errors need to be represented.
Example of custom exception:
class AgeNotValidException extends Exception {
public AgeNotValidException(String message) {
super(message);
}
}
Example of handling:
try {
int age = 15;
if (age < 18) {
throw new AgeNotValidException("Age must be 18 or above.");
}
} catch (AgeNotValidException e) {
System.out.println(e.getMessage());
}
Working / Process
1. Write risky code inside a try block
Place statements that may produce exceptions, such as file access, arithmetic operations, array access, or user input validation, inside try.
2. Provide one or more catch blocks
Define how each expected exception should be handled. Each catch block should match a specific exception type and respond appropriately.
3. Use finally, throw, or throws when needed
Add finally for cleanup, use throw to raise your own exception, and use throws to pass the responsibility of handling exceptions to another method.
Example:
public class Demo {
public static void main(String[] args) {
try {
int[] arr = {1, 2, 3};
System.out.println(arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index is invalid.");
} finally {
System.out.println("Program ended safely.");
}
}
}
Process diagram:
Risky code
|
v
Exception occurs?
|
Yes ------------------> Catch block handles it
|
No -------------------> Normal flow continues
|
v
Finally block executes
Advantages / Applications
Prevents abnormal program termination
Proper exception handling allows programs to continue running or end gracefully instead of crashing unexpectedly.
Improves code readability and maintenance
By separating error-handling code from normal logic, programs become cleaner, easier to read, and simpler to modify.
Useful in real-world software systems
It is widely used in file handling, database operations, network communication, input validation, banking systems, web applications, and multithreaded programs where failures must be managed safely.
Summary
- Exceptional handling is a way to manage runtime problems safely in a program.
- Java uses
try,catch,finally,throw, andthrowsfor handling exceptions. - It helps a program avoid crashing and supports clean, reliable error management.
- Important terms to remember: exception, checked exception, unchecked exception,
try,catch,finally,throw,throws