Java Exception Indepth Research

The exception mechanism is how the program is handled when the program meet an error. It provides a safe exit method for java program. When an error occurs, the program executing process changes, and the control of the program is transferred to the exception handler.

Exception handling process

When the program throws an exception, the program will jumps out of the code that cause it. Java virtual machine will find the related catch block which can handle it. If found, execute the java code in the catch block and exit the java code in try block. If not found, then after the java code in “finally block” execute, the program will throw it out to it’s parent class.

Class structure

java exception structure

From above picture we can see that Throwable is the base class, Error and Exception inherit Throwable,  RuntimeException and IOException inherit Exception. We will explain each of them in below list.

Error

Error indicates that the program meet a very serious, unrecoverable error at run time. In such case the application can only stop running. Error is an UncheckedException, the compiler will not check whether the error is handled or not in the program. You do not have to capture the error also. Generally you do not need to throw an Error in your java code.

RuntimeException

Java Exception include RuntimeException and others that are not RuntimeException. It is an UncheckedException. Java compiler will not check whether the java code process RuntimeException or not. You do not need to catch it in java code and do not need to declare it in method declaration. When a RuntimeException occurs, it indicates that a programming error has occurred in the program, so you should find the error and fix it instead of catching the RuntimeException.

CheckedException

This is also the most used in java programming. They all inherited from Exception class except RuntimeException. Such as IOException and ClassNotFoundException in above picture. JAVA language specifies that the CheckedException must be processed, the compiler will check it. You can either declare them in java method declaration, or use the catch statement to catch it to process, otherwise it will not pass compiler’s check.

Throws an exception when declaring a method

Grammar: throws

READ :   Java String Example

Why should we throw it at method declaration?

Whether the method throws an exception or not is as important as the type of return value of the method. Assuming that a method throws an exception but does not declare it, then when java code call this method, it will not have to write code to handle it also. So, once occurred, there is not any catch block that can control it.

Why thrown CheckedException?

RuntimeException and Error can be generated in any code, they do not need to be thrown by java programmer. When it occurred, a corresponding error will be thrown automatically. When your java code encounter Error or RuntimeException, there must have logical error in java code.

Only the CheckedException is what a programmer should concern with. The program should and should only throw or process it.

How to throw in method body?

Grammar: throw

For an exception object, the really useful information is it’s class type. For example, if it’s class type is ClassCastException, then the class is more useful than the object. So when you choose which exception to catch, the most critical is to select the class that can clearly explain the abnormal situation.

Exception objects usually have two constructors : One is a parameter-less constructor, the other is a constructor with a string input parameter, the string parameter provide the extra explanation to the caller.

Why do you need to create your own?

When Java built-in exception can not clearly explain the abnormal situation, you need to create your own.

The difference between throw and throws

From below java code example, you can see when and how to use throw and throws in java method.

public class TestThrowException {

public static void main(String[] args) {
 /* Call the method with the throws declaration, 
 * you must explicitly catch the exception it thrown.
 * Otherwise, you must throw it again in the main method. */
 try 
 { 
 throwCheckedException(true); 
 }catch(Exception ex) 
 { 
 System.out.println("CheckedException catched.");
 ex.printStackTrace(); 
 } 
 
 
 /* Call the method that throws the RuntimeException.
 * You can either explicitly capture or ignore it. */
 throwRuntimeException(false);
 
 System.out.println("Program finished.");
 }

/* Throws at method declaration. */
 public static void throwCheckedException(boolean checkedException) throws Exception 
 { 
 if(checkedException) 
 { 
 /* Throw CheckedException. */
 throw new Exception("This is a thrown CheckedException. "); 
 } 
 } 
 
 /* RuntimeException do not need to be thrown in method declaration. */
 public static void throwRuntimeException(boolean checkedException) 
 { 
 if (!checkedException) 
 { 
 /* Throw RuntimeException. */
 throw new RuntimeException("This is a RuntimeException. "); 
 } 
 } 
}

Added: Another style of the throwCheckedException method is as following:

 public static void throwCheckedException(boolean checkedException)
 { 
 if(checkedException) 
 { 
 try
 {
 /* Throw CheckedException. */
 throw new Exception("This is a thrown CheckedException. "); 
 }catch(Exception ex)
 {
 ex.printStackTrace();
 }
 } 
 }

Note: Now do not need try catch block in the main method because throwCheckedException method catch the thrown exception inside.

READ :   Java TimeZone Example

Should you throw it at the method declaration or catch it in the method body?

Handling principles: catch and handle exceptions that you know how to handle, and throw those ones that you do not know.

Use the finally block to release the resource

The finally keyword ensures that the java code in finally block will be executed regardless of how the program leaves the try block. The finally block will be entered in the following three cases:

  1. The try block java code completes normally.
  2. Try block java code throws an exception.
  3. Execute return, break, continue in the try block.

So, when you need a place to execute the code that must be executed in any case, you can put the code in the finally block. When your program uses external resources, such as database connections, files, etc. You must write the code that releases these resources in the finally block.

It is important to note that you had better do not throw exceptions in a finally block. JAVA handling mechanism ensures that the code in finally block should be executed first and then leave the try block.

So when an exception occurs in the try block, the JAVA virtual machine first go to the finally block to execute the code in it. After that, it will be thrown out.

If the exception is thrown in the finally block, then the exception occurred in the try block can not be thrown. The exception that is caught by the external java code will show the error message in the finally block, and the real error information in the try block is lost.

(Visited 78 times, 1 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.