1. How to handle Exceptions.
- Once Exception occurs in the program, we need to handle otherwise the program (thread/ flow) will be terminated.
- Five keywords are used in exception handling: try, catch, finally, throws and throw (take note that there is a difference between throw and throws).
- Java’s exception handling consists of three operations:
- Declaring exceptions
- Throwing an exception
- Catching an exception.
2. How to catch an Exceptions.
- Once Exception occurs in the program, we need to handle otherwise the program (thread) will be terminated.
- We need to use try-catch block for exception handling.
- Syntax of try-catch follows
try {
// main logic, uses methods that may throw Exceptions ...... } catch (Exception1 ex) { // error handler for Exception1 ...... } catch (Exception2 ex) { // error handler for Exception2 ...... } finally { // finally is optional // clean up codes, always executed regardless of exceptions ...... } |
- Try block contains the main logic to execute, if any exception occurs in the code of try block then jvm creates exception object and throws that object from try block, remaining code will not execute.
- Catch block will catch that exception object and executes the catch block code.
- After executing catch block, finally block will execute.
- If no exception occurs during the running of the try-block, all the catch-blocks are skipped, and finally-block will be executed after the try-block.
- If one of the statements in the try-block throws an exception, the Java runtime ignores the rest of the statements in the try-block, and begins searching for a matching exception handler.
- It matches the exception type with each of the catch-blocks sequentially. If a catch-block catches that exception class or catches a superclass of that exception, the statement in that catch-block will be executed.
- The statements in the finally-block are then executed after that catch-block.
- The program continues into the next statement after the try-catch-finally, unless it is pre-maturely terminated or branch-out.
- If none of the catch-block matches, the exception will be passed up the call stack.
- The current method executes the finally clause (if any) and popped off the call stack. The caller follows the same procedures to handle the exception.
- The finally block is almost certain to be executed, regardless of whether or not exception occurs (unless JVM encountered a severe error or a System.exit() is called in the catch block).
3. Try-catch block rules.
- A try-block must be accompanied by at least one catch-block or a finally-block.
- You can have multiple catch-blocks. Each catch-block catches only one type of exception.
- A catch block requires one argument, which is a throwable object (i.e., a subclass of java.lang.Throwable), as follows:
catch (AThrowableSubClass aThrowableObject) {
// exception handling codes } |
- You can use the following methods to retrieve the type of the exception and the state of the program from the Throwable object.
- printStackTrace()
try {
Scanner in = new Scanner(new File("test.in")); // process the file here ...... } catch (FileNotFoundException ex) { ex.printStackTrace(); } |
- We can also use printStackTrace(PrintStream s) or printStackTrace(PrintWriter s).
- getMessage(): Returns the message specified if the object is constructed using constructor Throwable(String message).
- toString(): Returns a short description of this Throwable object, consists of the name of the class, a colon ':', and a message from getMessage().
- A catch block catching a specific exception class can also catch its subclasses.
- Hence, catch(Exception ex) {...} catches all kinds of exceptions.
- However, this is not a good practice as the exception handler that is too general may unintentionally catches some subclasses' exceptions it does not intend to.
- The order of catch-blocks is important. A subclass must be caught (and placed in front) before its superclass. Otherwise, you receive a compilation error "exception XxxException has already been caught".
try {
Scanner in = new Scanner(new File("test.in")); // process the file here ...... } catch (Exception ex) { ex.printStackTrace(); }
catch (FileNotFoundException ex) {
ex.printStackTrace(); } |
- The finally-block is meant for cleanup code such as closing the file, database connection regardless of whether the try block succeeds. The finally block is always executed (unless the catch-block pre-maturely terminated the current method).
4. Can we write try block without catch block
- Yes, we can write any below combination of blocks.
- try-catch
- try-finally
- try-catch-finally
5. What is a Throwing an exception
- By default, if any error or exception occurs in the code, JVM create an exception object and throws the exception object.
- But if we want we can also create our own exception object and throws that object.
- For example, If user enters -ve age value, we can throw an exception explicitly.
- By using ‘throw’ keyword, we can throw an exception.
- At a time we can throw one exception only.
public void methodD() throws XxxException, YyyException { // method's signature
// method's body ... ... // XxxException occurs if ( ... ) throw new XxxException(...); // construct an XxxException object and throw to JVM ... // YyyException occurs if ( ... ) throw new YyyException(...); // construct an YyyException object and throw to JVM ... } |
- Note that the keyword to declare exception in the method's signature is "throws" and the keyword to throw an exception object within the method's body is "throw".
- ‘throws’ keyword is giving a notification to compiler about the current method may throws an exception.
public class MethodCallStackDemo {
public static void main(String[] args) { System.out.println("Enter main()"); methodA(); System.out.println("Exit main()"); } public static void methodA() { System.out.println("Enter methodA()");
try{
methodB();
}catch(Exception e){....}
System.out.println("Exit methodA()"); } public static void methodB() throws Exception{ System.out.println("Enter methodB()"); methodC(); System.out.println("Exit methodB()"); } public static void methodC() throws Exception{ System.out.println("Enter methodC()"); System.out.println("Exit methodC()"); } } |
6. How Exception handling will work?
- When an error occurs within a method, the method creates an object and hands it off to the runtime system.
- The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred.
- Creating an exception object and handing it to the runtime system is called throwing an exception.
- After a method throws an exception, the runtime system attempts to find something to handle it.
- The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred.The list of methods is known as the call stack (see the next figure)
- The runtime system searches the call stack for a method that contains a block of code that can handle the exception.
- This block of code is called an exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called.
- When an appropriate handler is found, the runtime system passes the exception to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler.
- The exception handler chosen is said to catch the exception.
- If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, as shown in the next figure, the runtime system (and, consequently, the program) terminates.
No comments:
Post a Comment