Exception Handling in Java
Exception handling in Java is one of the most powerful mechanisms for handling runtime errors so that the normal flow of the application can be maintained.
What is 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. Java Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.
Why Handle Exceptions?
Handling exceptions is crucial because it helps you:
- Prevent program crashes: Instead of letting the program crash, you can catch and handle exceptions gracefully.
- Debugging: Exceptions give you a clue about what went wrong and where.
- Maintainable code: Properly handled exceptions make your code easier to read and maintain.
Hierarchy of Java Exception classes
The Throwable class is at the top of the exception hierarchy following which are the subclasses-Error and Exception. Error and Exception should not be confused as same because there is a huge difference between these two classes.
Types of Java Exceptions
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 Exceptions:
- These exceptions are checked at compile-time.
- If your code might throw a checked exception, you must handle it using a try-catch block or declare it using the throws keyword.
- Example: IOException, SQLException.
Unchecked Exceptions:
- These exceptions are not checked at compile-time, they occur at runtime.
- They usually result from programming errors, such as logic mistakes or improper use of an API.
- Example: NullPointerException, ArrayIndexOutOfBoundsException.
Errors:
- Errors are serious problems that a reasonable application should not try to catch.
- Example: OutOfMemoryError, StackOverflowError.
Java Exception Keywords
Java provides five keywords that are used to handle the exception. The following table describes each.
Keyword | Description |
---|---|
try | The "try" keyword is used to specify a block where we should place an exception code. It means we can't use try block alone. The try block must be followed by either catch or finally. |
catch | The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later. |
finally | The "finally" block is used to execute the necessary code of the program. It is executed whether an exception is handled or not. |
throw | The "throw" keyword is used to throw an exception. |
throws | The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the method. It doesn't throw an exception. It is always used with method signature. |
Comments
Post a Comment