What is an exception explain various causes of exceptions?
An exception is an abnormal event that arises during the execution of the program and disrupts the normal flow of the program. Abnormality do occur when your program is running. For example, you might expect the user to enter an integer, but receive a text string; or an unexpected I/O error pops up at runtime. What really matters is "what happens after an abnormality occurred?" In other words, "how the abnormal situations are handled by your program." If these exceptions are not handled properly, the program terminates abruptly and may cause severe consequences. For example, the network connections, database connections and files may remain opened; database and file records may be left in an inconsistent state. Show Java has a built-in mechanism for handling runtime errors, referred to as exception handling. This is to ensure that you can write robust programs for mission-critical applications. Older programming languages such as C have some drawbacks in exception handing. For example, suppose the programmer wishes to open a file for processing:
Java overcomes these drawbacks by building the exception handling into the language rather than leaving it to the discretion of the programmers:
Let's look into these three points in more details. Point 1: Exceptions must be DeclaredAs an example, suppose that you want to use a 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 244 to perform formatted input from a disk file. The signature of the 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 245's constructor with a 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 246 argument is given as follows: public Scanner(File source) throws FileNotFoundException; The method's signature informs the programmers that an exceptional condition "file not found" may arise. By declaring the exceptions in the method's signature, programmers are made to aware of the exceptional conditions in using the method. Point 2: Exceptions must be HandledIf a method declares an exception in its signature, you cannot use this method without handling the exception - you can't compile the program. Example 1: The program did not handle the exception declared, resutled in compilation error. ScannerFromFile.java:5: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown Scanner in = new Scanner(new File("test.in")); ^ To use a method that declares an exception in its signature, you MUST either:
Example 2: Catch the exception via a " 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 247" (or " 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 243") construct. If the file cannot be found, the exception is caught in the catch-block. In this example, the error handler simply prints the stack trace, which provides useful information for debugging. In some situations, you may need to perform some clean-up operations, or open another file instead. Take note that the main logic in the try-block is separated from the error handling codes in the catch-block. Example 3: You decided not to handle the exception in the current method, but throw the exception up the call stack for the next higher-level method to handle. In this example, you decided not to handle the 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()"); methodB(); System.out.println("Exit methodA()"); } public static void methodB() { System.out.println("Enter methodB()"); methodC(); System.out.println("Exit methodB()"); } public static void methodC() { System.out.println("Enter methodC()"); System.out.println("Exit methodC()"); } }1 thrown by the 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()"); methodB(); System.out.println("Exit methodA()"); } public static void methodB() { System.out.println("Enter methodB()"); methodC(); System.out.println("Exit methodB()"); } public static void methodC() { System.out.println("Enter methodC()"); System.out.println("Exit methodC()"); } }2 method (with 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 247). Instead, the caller of 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()"); methodB(); System.out.println("Exit methodA()"); } public static void methodB() { System.out.println("Enter methodB()"); methodC(); System.out.println("Exit methodB()"); } public static void methodC() { System.out.println("Enter methodC()"); System.out.println("Exit methodC()"); } }2 - the 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()"); methodB(); System.out.println("Exit methodA()"); } public static void methodB() { System.out.println("Enter methodB()"); methodC(); System.out.println("Exit methodB()"); } public static void methodC() { System.out.println("Enter methodC()"); System.out.println("Exit methodC()"); } }5 method - declares in its signature " 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()"); methodB(); System.out.println("Exit methodA()"); } public static void methodB() { System.out.println("Enter methodB()"); methodC(); System.out.println("Exit methodB()"); } public static void methodC() { System.out.println("Enter methodC()"); System.out.println("Exit methodC()"); } }6", which means that this exception will be thrown up the call stack, for the next higher-level method to handle. In this case, the next higher-level method of 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()"); methodB(); System.out.println("Exit methodA()"); } public static void methodB() { System.out.println("Enter methodB()"); methodC(); System.out.println("Exit methodB()"); } public static void methodC() { System.out.println("Enter methodC()"); System.out.println("Exit methodC()"); } }5 is the JVM, which simply terminates the program and prints the stack trace. Point 3: Main logic is separated from the exception handling codesAs shown in Example 2, the main logic is contained in the try-block, while the exception handling codes are kept in the catch-block(s) separated from the main logic. This greatly improves the readability of the program. For example, a Java program for file processing could be as follows: Method Call StackA typical application involves many levels of method calls, which is managed by a so-called method call stack. A stack is a last-in-first-out queue. In the following example, 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()"); methodB(); System.out.println("Exit methodA()"); } public static void methodB() { System.out.println("Enter methodB()"); methodC(); System.out.println("Exit methodB()"); } public static void methodC() { System.out.println("Enter methodC()"); System.out.println("Exit methodC()"); } }5 method invokes 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()"); methodB(); System.out.println("Exit methodA()"); } public static void methodB() { System.out.println("Enter methodB()"); methodC(); System.out.println("Exit methodB()"); } public static void methodC() { System.out.println("Enter methodC()"); System.out.println("Exit methodC()"); } }9; 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()"); methodB(); System.out.println("Exit methodA()"); } public static void methodB() { System.out.println("Enter methodB()"); methodC(); System.out.println("Exit methodB()"); } public static void methodC() { System.out.println("Enter methodC()"); System.out.println("Exit methodC()"); } }9 calls Enter main() Enter methodA() Enter methodB() Enter methodC() Exit methodC() Exit methodB() Exit methodA() Exit main()1; Enter main() Enter methodA() Enter methodB() Enter methodC() Exit methodC() Exit methodB() Exit methodA() Exit main()1 calls Enter main() Enter methodA() Enter methodB() Enter methodC() Exit methodC() Exit methodB() Exit methodA() Exit main()3. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 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()"); methodB(); System.out.println("Exit methodA()"); } public static void methodB() { System.out.println("Enter methodB()"); methodC(); System.out.println("Exit methodB()"); } public static void methodC() { System.out.println("Enter methodC()"); System.out.println("Exit methodC()"); } } Enter main() Enter methodA() Enter methodB() Enter methodC() Exit methodC() Exit methodB() Exit methodA() Exit main() As seen from the output, the sequence of events is:
suppose that we modify Enter main() Enter methodA() Enter methodB() Enter methodC() Exit methodC() Exit methodB() Exit methodA() Exit main()3 to carry out a "divide-by-0" operation, which triggers a Enter main() Enter methodA() Enter methodB() Enter methodC() Exception in thread "main" java.lang.ArithmeticException: / by zero at MethodCallStackDemo.methodC(MethodCallStackDemo.java:22) at MethodCallStackDemo.methodB(MethodCallStackDemo.java:16) at MethodCallStackDemo.methodA(MethodCallStackDemo.java:10) at MethodCallStackDemo.main(MethodCallStackDemo.java:4)6: The exception message clearly shows the method call stack trace with the relevant statement line numbers: Enter main() Enter methodA() Enter methodB() Enter methodC() Exception in thread "main" java.lang.ArithmeticException: / by zero at MethodCallStackDemo.methodC(MethodCallStackDemo.java:22) at MethodCallStackDemo.methodB(MethodCallStackDemo.java:16) at MethodCallStackDemo.methodA(MethodCallStackDemo.java:10) at MethodCallStackDemo.main(MethodCallStackDemo.java:4) Enter main() Enter methodA() Enter methodB() Enter methodC() Exception in thread "main" java.lang.ArithmeticException: / by zero at MethodCallStackDemo.methodC(MethodCallStackDemo.java:22) at MethodCallStackDemo.methodB(MethodCallStackDemo.java:16) at MethodCallStackDemo.methodA(MethodCallStackDemo.java:10) at MethodCallStackDemo.main(MethodCallStackDemo.java:4)7 triggers an Enter main() Enter methodA() Enter methodB() Enter methodC() Exception in thread "main" java.lang.ArithmeticException: / by zero at MethodCallStackDemo.methodC(MethodCallStackDemo.java:22) at MethodCallStackDemo.methodB(MethodCallStackDemo.java:16) at MethodCallStackDemo.methodA(MethodCallStackDemo.java:10) at MethodCallStackDemo.main(MethodCallStackDemo.java:4)6. As it does not handle this exception, it popped off from the call stack immediately. Enter main() Enter methodA() Enter methodB() Enter methodC() Exception in thread "main" java.lang.ArithmeticException: / by zero at MethodCallStackDemo.methodC(MethodCallStackDemo.java:22) at MethodCallStackDemo.methodB(MethodCallStackDemo.java:16) at MethodCallStackDemo.methodA(MethodCallStackDemo.java:10) at MethodCallStackDemo.main(MethodCallStackDemo.java:4)9 also does not handle this exception and popped off the call stack. So does 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()"); methodB(); System.out.println("Exit methodA()"); } public static void methodB() { System.out.println("Enter methodB()"); methodC(); System.out.println("Exit methodB()"); } public static void methodC() { System.out.println("Enter methodC()"); System.out.println("Exit methodC()"); } }9 and 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()"); methodB(); System.out.println("Exit methodA()"); } public static void methodB() { System.out.println("Enter methodB()"); methodC(); System.out.println("Exit methodB()"); } public static void methodC() { System.out.println("Enter methodC()"); System.out.println("Exit methodC()"); } }5 method. The 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()"); methodB(); System.out.println("Exit methodA()"); } public static void methodB() { System.out.println("Enter methodB()"); methodC(); System.out.println("Exit methodB()"); } public static void methodC() { System.out.println("Enter methodC()"); System.out.println("Exit methodC()"); } }5 method passes back to JVM, which abruptly terminates the program and print the call stack trace, as shown. Exception & Call StackWhen an exception occurs inside a Java method, the method creates an public void methodD() throws XxxException, YyyException { ...... }3 object and passes the public void methodD() throws XxxException, YyyException { ...... }3 object to the JVM (in Java term, the method " public void methodD() throws XxxException, YyyException { ...... }5" an public void methodD() throws XxxException, YyyException { ...... }3). The public void methodD() throws XxxException, YyyException { ...... }3 object contains the type of the exception, and the state of the program when the exception occurs. The JVM is responsible for finding an exception handler to process the public void methodD() throws XxxException, YyyException { ...... }3 object. It searches backward through the call stack until it finds a matching exception handler for that particular class of public void methodD() throws XxxException, YyyException { ...... }3 object (in Java term, it is called " 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 200" the public void methodD() throws XxxException, YyyException { ...... }3). If the JVM cannot find a matching exception handler in all the methods in the call stack, it terminates the program. This process is illustrated as follows. Suppose that 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 202 encounters an abnormal condition and throws a 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 203 to the JVM. The JVM searches backward through the call stack for a matching exception handler. It finds 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()"); methodB(); System.out.println("Exit methodA()"); } public static void methodB() { System.out.println("Enter methodB()"); methodC(); System.out.println("Exit methodB()"); } public static void methodC() { System.out.println("Enter methodC()"); System.out.println("Exit methodC()"); } }9 having a 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 203 handler and passes the exception object to the handler. Notice that Enter main() Enter methodA() Enter methodB() Enter methodC() Exit methodC() Exit methodB() Exit methodA() Exit main()3 and Enter main() Enter methodA() Enter methodB() Enter methodC() Exit methodC() Exit methodB() Exit methodA() Exit main()1 are required to declare " 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 208 in their method signatures in order to compile the program. Exception Classes - Throwable, Error, Exception & RuntimeExceptionThe figure below shows the hierarchy of the public void methodD() throws XxxException, YyyException { ...... }3 classes. The base class for all public void methodD() throws XxxException, YyyException { ...... }3 objects is Start of the main logic Try opening a file ... File Not Found caught ... finally-block runs regardless of the state of exception After try-catch-finally, life goes on...1, together with its two subclasses Start of the main logic Try opening a file ... File Not Found caught ... finally-block runs regardless of the state of exception After try-catch-finally, life goes on...2 and Start of the main logic Try opening a file ... File Not Found caught ... finally-block runs regardless of the state of exception After try-catch-finally, life goes on...3.
Checked vs. Unchecked ExceptionsAs illustrated, the subclasses of Start of the main logic Try opening a file ... File Not Found caught ... finally-block runs regardless of the state of exception After try-catch-finally, life goes on...4 and public Scanner(File source) throws FileNotFoundException;01 are known as unchecked exceptions. These exceptions are not checked by the compiler, and hence, need not be caught or declared to be thrown in your program. This is because there is not much you can do with these exceptions. For example, a "divide by 0" triggers an Enter main() Enter methodA() Enter methodB() Enter methodC() Exception in thread "main" java.lang.ArithmeticException: / by zero at MethodCallStackDemo.methodC(MethodCallStackDemo.java:22) at MethodCallStackDemo.methodB(MethodCallStackDemo.java:16) at MethodCallStackDemo.methodA(MethodCallStackDemo.java:10) at MethodCallStackDemo.main(MethodCallStackDemo.java:4)6, array index out-of-bound triggers an public Scanner(File source) throws FileNotFoundException;03 which are really programming logical errors that shall be been fixed in compiled-time, rather than leaving it to runtime exception handling. All the other exception are called checked exceptions. They are checked by the compiler and must be caught or declared to be thrown. Exception Handling OperationsFive keywords are used in exception handling: public Scanner(File source) throws FileNotFoundException;04, 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 200, public Scanner(File source) throws FileNotFoundException;06, public Scanner(File source) throws FileNotFoundException;07 and public void methodD() throws XxxException, YyyException { ...... }5 (take note that there is a difference between public void methodD() throws XxxException, YyyException { ...... }5 and public Scanner(File source) throws FileNotFoundException;07). Java’s exception handling consists of three operations:
Declaring ExceptionsA Java method must declare in its signature the types of checked exception it may "throw" from its body, via the keyword "throws". For example, suppose that 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 202 is defined as follows: The method's signature indicates that running 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 202 may encounter two checked exceptions: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 203 and public Scanner(File source) throws FileNotFoundException;14. In other words, some of the abnormal conditions inside 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 202 may trigger 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 203 or public Scanner(File source) throws FileNotFoundException;14. Exceptions belonging to Start of the main logic Try opening a file ... File Not Found caught ... finally-block runs regardless of the state of exception After try-catch-finally, life goes on...4, public Scanner(File source) throws FileNotFoundException;01 and their subclasses need not be declared. These exceptions are called unchecked exceptions because they are not checked by the compiler. Throwing an ExceptionWhen a Java operation encounters an abnormal situation, the method containing the erroneous statement shall create an appropriate public void methodD() throws XxxException, YyyException { ...... }3 object and throw it to the Java runtime via the statement " public Scanner(File source) throws FileNotFoundException;21". For example, Note that the keyword to declare exception in the method's signature is " public Scanner(File source) throws FileNotFoundException;07" and the keyword to throw an exception object within the method's body is " public void methodD() throws XxxException, YyyException { ...... }5". Catching an ExceptionWhen a method throws an exception, the JVM searches backward through the call stack for a matching exception handler. Each exception handler can handle one particular class of exception. An exception handler handles a specific class can also handle its subclasses. If no exception handler is found in the call stack, the program terminates. For example, suppose 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 202 declares that it may throw 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 203 and public Scanner(File source) throws FileNotFoundException;14 in its signature, as follows: public void methodD() throws XxxException, YyyException { ...... } To use 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 202 in your program (says in Enter main() Enter methodA() Enter methodB() Enter methodC() Exit methodC() Exit methodB() Exit methodA() Exit main()3), you can either:
try-catch-finallyThe syntax of try-catch-finally is: 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 the1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 200-block matches, the exception will be passed up the call stack. The current method executes the public Scanner(File source) throws FileNotFoundException;06 clause (if any) and popped off the call stack. The caller follows the same procedures to handle the exception. The public Scanner(File source) throws FileNotFoundException;06 block is almost certain to be executed, regardless of whether or not exception occurs (unless JVM encountered a severe error or a public Scanner(File source) throws FileNotFoundException;41 is called in the 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 200 block). Example 11 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 This is the output when the 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()"); methodB(); System.out.println("Exit methodA()"); } public static void methodB() { System.out.println("Enter methodB()"); methodC(); System.out.println("Exit methodB()"); } public static void methodC() { System.out.println("Enter methodC()"); System.out.println("Exit methodC()"); } }1 triggered: Start of the main logic Try opening a file ... File Not Found caught ... finally-block runs regardless of the state of exception After try-catch-finally, life goes on... This is the output when no exception triggered: public Scanner(File source) throws FileNotFoundException;0 Example 21 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 public Scanner(File source) throws FileNotFoundException;2 try-catch-finally
What if I really don't care about the exceptionsCertainly not advisable other than writing toy programs. But to bypass the compilation error messages triggered by methods declaring unchecked exceptions, you could declare " public Scanner(File source) throws FileNotFoundException;62" in your 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()"); methodB(); System.out.println("Exit methodA()"); } public static void methodB() { System.out.println("Enter methodB()"); methodC(); System.out.println("Exit methodB()"); } public static void methodC() { System.out.println("Enter methodC()"); System.out.println("Exit methodC()"); } }5 (and other methods), as follows: Overriding and Overloading MethodsAn overriding method must have the same argument list and return-type (or subclass of its original from JDK 1.5). An overloading method must have different argument list, but it can have any return-type. An overriding method cannot have more restricted access. For example, a method with public Scanner(File source) throws FileNotFoundException;64 access may be overridden to have protected or public access but not public Scanner(File source) throws FileNotFoundException;65 or default access. This is because an overridden method is considered to be a replacement of its original, hence, it cannot be more restrictive. An overriding method cannot declare exception types that were not declared in its original. However, it may declare exception types are the same as, or subclass of its original. It needs not declare all the exceptions as its original. It can throw fewer exceptions than the original, but not more. An overloading method must be differentiated by its argument list. It cannot be differentiated by the return-type, the exceptions, and the modifier, which is illegal. It can have any return-type, access modifier, and exceptions, as long as it can be differentiated by the argument list. Common Exception ClassesArrayIndexOutOfBoundsException: thrown by JVM when your code uses an array index, which is is outside the array's bounds. For example, public Scanner(File source) throws FileNotFoundException;3 public Scanner(File source) throws FileNotFoundException;4 NullPointerException: thrown by the JVM when your code attempts to use a null reference where an object reference is required. For example, public Scanner(File source) throws FileNotFoundException;5 public Scanner(File source) throws FileNotFoundException;6 NumberFormatException: Thrown programmatically (e.g., by public Scanner(File source) throws FileNotFoundException;66) when an attempt is made to convert a string to a numeric type, but the string does not have the appropriate format. For example, public Scanner(File source) throws FileNotFoundException;7 public Scanner(File source) throws FileNotFoundException;8 ClassCastException: thrown by JVM when an attempt is made to cast an object reference fails. For example, public Scanner(File source) throws FileNotFoundException;9 ScannerFromFile.java:5: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown Scanner in = new Scanner(new File("test.in")); ^0 IllegalArgumentException: thrown programmatically to indicate that a method has been passed an illegal or inappropriate argument. You could re-use this exception for your own methods. IllegalStateException: thrown programmatically when a method is invoked and the program is not in an appropriate state for that method to perform its task. This typically happens when a method is invoked out of sequence, or perhaps a method is only allowed to be invoked once and an attempt is made to invoke it again. NoClassDefFoundError: thrown by the JVM or class loader when the definition of a class cannot be found. Prior to JDK 1.7, you will see this exception call stack trace if you try to run a non-existent class. JDK 1.7 simplifies the error message to "Error: Could not find or load main class xxx". Creating Your Own Exception ClassesYou should try to reuse the public void methodD() throws XxxException, YyyException { ...... }3 classes provided in the JDK, e.g., public Scanner(File source) throws FileNotFoundException;68, Enter main() Enter methodA() Enter methodB() Enter methodC() Exception in thread "main" java.lang.ArithmeticException: / by zero at MethodCallStackDemo.methodC(MethodCallStackDemo.java:22) at MethodCallStackDemo.methodB(MethodCallStackDemo.java:16) at MethodCallStackDemo.methodA(MethodCallStackDemo.java:10) at MethodCallStackDemo.main(MethodCallStackDemo.java:4)6, Start of the main logic Try opening a file ... File Not Found caught ... finally-block runs regardless of the state of exception After try-catch-finally, life goes on...9, and public Scanner(File source) throws FileNotFoundException;71. But you can always create you own public void methodD() throws XxxException, YyyException { ...... }3 classes by extending from the class public void methodD() throws XxxException, YyyException { ...... }3 or one of its subclasses. Note that public Scanner(File source) throws FileNotFoundException;01 and its subclasses are not checked by the compiler and need not be declared in the method's signature. Therefore, use them with care, as you will not be informed and may not be aware of the exceptions that may occur by using that method (and therefore do not have the proper exception handling codes) – a bad software engineering practice. ExampleScannerFromFile.java:5: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown Scanner in = new Scanner(new File("test.in")); ^1 The output is as follows: ScannerFromFile.java:5: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown Scanner in = new Scanner(new File("test.in")); ^2 Assertion (JDK 1.4)JDK 1.4 introduced a new keyword called public Scanner(File source) throws FileNotFoundException;75, to support the so-called assertion feature. Assertion enables you to test your assumptions about your program logic (such as pre-conditions, post-conditions, and invariants). Each assertion contains a boolean expression that you believe will be true when the program executes. If it is not true, the JVM will throw an public Scanner(File source) throws FileNotFoundException;76. This error signals you that you have an invalid assumption that needs to be fixed. Assertion is much better than using if-else statements, as it serves as proper documentation on your assumptions, and it does not carry performance liability in the production environment (to be discussed later). The public Scanner(File source) throws FileNotFoundException;75 statement has two forms: ScannerFromFile.java:5: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown Scanner in = new Scanner(new File("test.in")); ^3 When the runtime execute the assertion, it first evaluates the public Scanner(File source) throws FileNotFoundException;78. If the value is public Scanner(File source) throws FileNotFoundException;79, nothing happens. If it is public Scanner(File source) throws FileNotFoundException;80, the runtime throws an public Scanner(File source) throws FileNotFoundException;76, using the no-argument constructor (in the first form) or public Scanner(File source) throws FileNotFoundException;82 as the argument to the constructor (in the second form). If an object is passed as the public Scanner(File source) throws FileNotFoundException;83, the object's public Scanner(File source) throws FileNotFoundException;50 will be called to obtain the message string. Assertion is useful in detecting bugs. It also serves to document the inner workings of you program (e.g., pre-conditions and post-conditions) and enhances the maintainability. One good candidate for assertion is the switch-case statement where the programmer believes that one of the cases will be selected, and the default-case is not plausible. For example, ScannerFromFile.java:5: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown Scanner in = new Scanner(new File("test.in")); ^4 Assertion, by default, are disabled to ensure that they are not a performance liability in the production environment. To enable assertion, use the runtime command-line option public Scanner(File source) throws FileNotFoundException;85 (or public Scanner(File source) throws FileNotFoundException;86). In the above example, " public Scanner(File source) throws FileNotFoundException;87" always triggers an public Scanner(File source) throws FileNotFoundException;76. However, the output is different, depending on whether assertion is enabled or disabled. ScannerFromFile.java:5: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown Scanner in = new Scanner(new File("test.in")); ^5 ScannerFromFile.java:5: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown Scanner in = new Scanner(new File("test.in")); ^6 ScannerFromFile.java:5: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown Scanner in = new Scanner(new File("test.in")); ^7 ScannerFromFile.java:5: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown Scanner in = new Scanner(new File("test.in")); ^8 In the above example, since the " public Scanner(File source) throws FileNotFoundException;87" always triggers an public Scanner(File source) throws FileNotFoundException;76, you could choose to public void methodD() throws XxxException, YyyException { ...... }5 an public Scanner(File source) throws FileNotFoundException;76. " public void methodD() throws XxxException, YyyException { ...... }5" is always enabled during runtime. ScannerFromFile.java:5: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown Scanner in = new Scanner(new File("test.in")); ^9 Another usage of assertion is to assert "internal invariants". In other words, to assert the possible values of an internal variable. For example, 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 240 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 241 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 242 Assertion can be used for verifying:
Pre-conditions of public methodsAssertion should not be used to check the validity of the arguments (pre-condition) passed into "public" method. It is because ScannerFromFile.java:5: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown Scanner in = new Scanner(new File("test.in")); ^00 methods are exposed and anyone could call this method with an invalid argument. Instead, use a ScannerFromFile.java:5: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown Scanner in = new Scanner(new File("test.in")); ^01 statement to check the argument and throw an ScannerFromFile.java:5: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown Scanner in = new Scanner(new File("test.in")); ^02 otherwise. On the other hand, public Scanner(File source) throws FileNotFoundException;65 methods are under your sole control and it is appropriate to assert the pre-conditions. For example, What is exception and what are the causes of exception?An exception is thrown for one of three reasons: An abnormal execution condition was synchronously detected by the Java virtual machine. Such conditions arise because: evaluation of an expression violates the normal semantics of the language, such as an integer divide by zero, as summarized in §15.6.
What is called exception?An exception is something that is left out or not done on purpose. An exception to a rule does not follow that rule. This word is used for all sorts of things that are not usual or usually allowed. The saying ”i before e except after c,” is about an exception to a spelling rule.
What are the 3 types of exceptions?There are three types of exception—the checked exception, the error and the runtime exception.
What is an exception answer?Explanation: The problems that might occur during execution of a program are known as exceptions. The exceptions are unexpected sometimes and can be predicted. Also, the exceptions should be always considered for a better program.
|