An exception is an abnormal condition that arises in a code sequence at run time.
Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.
Workflow

  • Program statements that you want to monitor for exceptions are contained within a try block. If an exception occurs within the try block, it is thrown.
  • Your code can catch this exception (using catch) and handle it in some rational manner. To manually throw an exception, use the keyword throw.
  • Any exception that is thrown out of a method must be specified as such by a throws clause. Any code that absolutely must be executed after a try block completes is put in a finally block.

Note: When you use multiple catch statements, it is important to remember that exception subclasses must come before any of their superclasses.
Exception Types

 

  • Throwable is at the top of the exception class hierarchy.
  • Throwable are two subclasses that partition exceptions into two distinct branches.
  • One branch is headed by Exception. This class is used for exceptional conditions that user programs should catch. This is also the class that you will subclass to create your own custom exception types.
  • The other branch is topped by Error, which defines exceptions that are not expected to be caught under normal circumstances by your program.

Throw:

  • Primitive types, such as int or char, as well as non-Throwable classes, such as String and Object, cannot be used as exceptions.
  • There are two ways you can obtain a Throwable object using a parameter in a catch clause, or creating one with the new operator.
  • The flow of execution stops immediately after the throw statement; any subsequent statements are not executed.
// Demonstrate throw.
class ThrowDemo {
    static void demoproc() {
        try {
            throw new NullPointerException("demo");
        } catch (NullPointerException e) {
            System.out.println("Caught inside demoproc.");
            throw e; // rethrow the exception
            System.out.println("This statement will not execute");
        }
    }
}

Throws:

  • If a method is capable of causing an exception that it does not handle, it must specify this behaviour so that callers of the method can guard themselves against that exception.
void checkThrow() throws IOException {
    int data = 1;
    System.out.println(data);
    throw new IOException("Throwing IO Exception");
}

Finally

  • Finally creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block.
  • The finally block will execute whether or not an exception is thrown.
  • If a finally block is associated with a try, the finally block will be executed upon conclusion of the try.

Note: If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

Creating Your Own Exception Subclasses

  • extends Exception to your custom Exception class
public class CustomException extends Exception {
    private static final long serialVersionUID = 1 L;
    CustomException(String msg) {
        super(msg);
    }
}

public class UserExceptionDemo {
    public static void getUserData() {
        try {
            Integer.parseInt("parseMe");
        } catch (NumberFormatException ne) {
            throw ne;
        } catch (Exception e) {
            throw e;
        }
    }

    public static void main(String[] args) throws CustomException {
        try {
            getUserData();
        } catch (Exception e) {
            // throwing custom Exception
            throw new CustomException("Parse exception " + e.getMessage());
            // Exception message: Parse exception For input string: "parseMe"
        }
    }
}
Categories: JAVA

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.