Monday, July 19, 2021

Java Exception Handling Tutorial

Exception Handling in Java provides a way to handle a situation when an exception is thrown by showing a meaningful message to the user and continue (or terminate) with the flow of the program.

How Java exception handling works

When an exceptional condition occurs with in a method, the method (where the exception occurred) creates an Exception Object and throws it. The created exception object contains information about the error, its type and the state of the program when the error occurred.

The method where the exception is thrown may handle that exception itself or pass it on. In case it passes it on, run time system goes through the method hierarchy that had been called to get to the current method to search for a method that can handle the exception.

If your program is not able to catch any particular exception, that will ultimately be processed by the default handler. The default handler displays a message describing the exception, prints a stack trace from the point at which the exception occurred, and terminates the program.

Five keywords used to manage Java exception handling

  • try- Any code that might throw an exception is enclosed within a try block.
  • catch- If an exception occurs in try block, catch block can provide exception handlers to handle it in a rational manner.
  • finally - The finally block always executes when the try block exits. So, any code that must execute after a try block is completed should be put in finally block.
  • throw- throw is used to manually thrown an exception.
  • throws- Any exception that is thrown in a method but not handled there must be specified in a throws clause.

General form of exception handling in Java

The general form of an exception-handling block is as given below.

try {
  // block of code
}
catch (ExceptionType1 expObj) {
  // exception handler for ExceptionType1
}
catch (ExceptionType2 expObj) {
  // exception handler for ExceptionType2
}
// ...
finally {
  // block of code to be executed after try block ends
}

Here, ExceptionType is the type of exception that has occurred

Exception Hierarchy in Java

Throwable class is the super class of all the exception classes in Java. Below Throwable class there are two subclasses which denotes two distinct branches of exceptions-

  • Exception- An Exception indicates that a problem has occurred, but it is not a serious system problem. The user programs you write will throw and catch Exceptions.
  • Error- It defines exceptions that are not expected to be caught by your program. Exceptions of type Error are used by the Java run-time system to indicate errors having to do with the run-time environment, itself.
    Examples of error are StackOverflowError, OutOfMemoryError etc.
Exception Hierarchy in Java

Kinds of exception in Java

  • Checked Exception- These are exceptional conditions that an application should anticipate and recover from.
  • RunTime Excpetion- These are exceptional conditions that are external to the application, and the application usually cannot anticipate or recover from them.
  • Error- It defines exceptions that are not expected to be caught by your program.

  • Error and runtime exceptions are collectively known as unchecked exceptions.

Please refer to checked exception Vs unchecked exception for detailed explanation of checked and unchecked exceptions.

Advantages of Exception Handling

  • To maintain the normal flow of the application.
  • Separation of concerns by separating error-handling code from regular code.
  • Providing a proper message for the failing condition.
  • Preventing the program from automatically terminating.

Topics discussed in this Java exception handling tutorial

  1. try-catch Block in Java Exception Handling
  2. finally Block in Java Exception Handling
  3. Multiple Catch Blocks in Java Exception Handling
  4. Nested Try Statements in Java Exception Handling
  5. throw Statement in Java Exception Handling
  6. throws Keyword in Java Exception Handling
  7. Exception Propagation in Java Exception Handling
  8. Java Exception Handling And Method Overriding
  9. Difference Between Checked And Unchecked Exceptions in Java
  10. Difference Between throw And throws in Java
  11. final Vs finally Vs finalize in Java
  12. Creating Custom Exception Class in Java
  13. Multi-Catch Statement in Java Exception Handling
  14. Try-With-Resources in Java Exception Handling
  15. Best Practices For Exception Handling in Java
  16. java.lang.ClassNotFoundException - Resolving ClassNotFoundException in Java
  17. java.lang.ClassCastException - Resolving ClassCastException in Java
  18. java.lang.UnsupportedClassVersionError - Resolving UnsupportedClassVersionError in Java
  19. Difference Between StackOverflowError and OutOfMemoryError in Java

>>>Return to Java Basics Tutorial Page

4 comments:

  1. You are doing great work, I would appreciate your efforts in helping us understand the concepts. I had a small doubt, throws clause is for the exceptions which are expected to be thrown by a method but not handled in the method is it? your explanation is little different from that. Can you help me understand which is correct.
    Thanks a lot!

    ReplyDelete
    Replies
    1. I said almost the same thing. A method will be called from some other method (may be main method). If you want to leave the task of exception handling to the calling method, in the called method you can just give the exceptions with throws clause.

      throws clause

      Delete
  2. very good explanation and helpful for understating the concepts.

    ReplyDelete