When a program violates the semantic constraints of the Java programming language, the Java Virtual Machine signals this error to the program as an exception. Show
An example of such a violation is an attempt to index outside the bounds of an array. Some programming languages and their implementations react to such errors by peremptorily terminating the program; other programming languages allow an implementation to react in an arbitrary or unpredictable way. Neither of these approaches is compatible with the design goals of the Java SE Platform: to provide portability and robustness. Instead, the Java programming language specifies that an exception will be thrown when semantic constraints are violated and will cause a non-local transfer of control from the point where the exception occurred to a point that can be specified by the programmer. An exception is said to be thrown from the point where it occurred and is said to be caught at the point to which control is transferred. Programs can also throw exceptions explicitly, using Explicit use of Every exception is represented by an
instance of the class During the process of throwing an exception, the Java Virtual Machine abruptly completes, one by one, any expressions, statements, method and constructor invocations, initializers, and field initialization expressions that have begun but not completed execution in the current thread. This process continues until a handler is found that indicates that it handles that particular exception by naming the class of the exception or a superclass of the class of the exception (§11.2). If no such handler is found, then the exception may be handled by one of a hierarchy of uncaught exception handlers (§11.3) - thus every effort is made to avoid letting an exception go unhandled. The exception mechanism of the Java SE Platform is integrated with its synchronization model (§17.1), so
that monitors are unlocked as 11.1. The Kinds and Causes of Exceptions11.1.1. The Kinds of ExceptionsAn exception is represented by an instance of the class The classes
The unchecked exception classes are the run-time exception classes and the error classes. The checked exception
classes are all exception classes other than the unchecked exception classes. That is, the checked exception classes are Programs can use the pre-existing exception classes of the Java SE Platform API in The class Note that a subclass of 11.1.2. The Causes of ExceptionsAn exception is thrown for one of three reasons:
11.1.3. Asynchronous ExceptionsMost exceptions occur synchronously as a result of an action by the thread in which they occur, and at a point in the program that is specified to possibly result in such an exception. An asynchronous exception is, by contrast, an exception that can potentially occur at any point in the execution of a program. Asynchronous exceptions occur only as a result of:
The Java SE Platform permits a small but bounded amount of execution to occur before an asynchronous exception is thrown. Asynchronous exceptions are rare, but proper understanding of their semantics is necessary if high-quality machine code is to be generated. The delay noted above is permitted to allow optimized code to detect and throw these exceptions at points where it is practical to handle them while obeying the semantics of the Java programming language. A simple implementation might poll for asynchronous exceptions at the point of each control transfer instruction. Since a program has a finite size, this provides a bound on the total delay in detecting an asynchronous exception. Since no asynchronous exception will occur between control transfers, the code generator has some flexibility to reorder computation between control transfers for greater performance. The paper Polling Efficiently on Stock Hardware by Marc Feeley, Proc. 1993 Conference on Functional Programming and Computer Architecture, Copenhagen, Denmark, pp. 179-187, is recommended as further reading. 11.2. Compile-Time Checking of ExceptionsThe Java programming language requires that a program contains handlers for
checked exceptions which can result from execution of a method or constructor (§8.4.6, §8.8.5). This compile-time checking for the presence of exception handlers is designed to reduce the number of exceptions
which are not properly handled. For each checked exception which is a possible result, the The checked exception classes
(§11.1.1) named in the The unchecked exception classes (§11.1.1) are exempted from compile-time checking. Error classes are exempted because they can occur at many points in the program and recovery from them is difficult or impossible. A program declaring such exceptions would be cluttered, pointlessly. Sophisticated programs may yet wish to catch and attempt to recover from some of these conditions. Run-time exception classes are exempted because, in the judgment of the designers of the Java programming language, having to declare such exceptions would not aid significantly in establishing the correctness of programs. Many of the operations and constructs of the Java programming language can result in exceptions at run time. The information available to a Java compiler, and the level of analysis a compiler performs, are usually not sufficient to establish that such run-time exceptions cannot occur, even though this may be obvious to the programmer. Requiring such exception classes to be declared would simply be an irritation to programmers. For example, certain code might implement a circular data structure that, by construction, can never
involve null references; the programmer can then be certain that a We say that a statement or expression can throw an exception class E if, according to the rules in §11.2.1 and §11.2.2, the execution of the statement or expression can result in an exception of class E being thrown. We say that a
11.2.1. Exception Analysis of ExpressionsA class instance creation expression (§15.9) can throw an exception class E iff either:
A method invocation expression (§15.12) can throw an exception class E iff either:
A lambda expression (§15.27) can throw no exception classes. For every other kind of expression, the expression can throw an exception class E iff one of its immediate subexpressions can throw E. Note that a method reference expression
(§15.13) of the form Primary 11.2.2. Exception Analysis of StatementsA For example, the statement A
A
An explicit constructor invocation statement (§8.8.7.1) can throw an exception class E iff either:
Any other statement S can throw an exception class E iff an expression or statement immediately contained in S can throw E. 11.2.3. Exception CheckingIt is a compile-time error if a method or constructor body can throw some exception class E when E is a checked exception class and E is not a subclass of some class declared in the It is a compile-time error if a lambda
body can throw some exception class E when E is a checked exception class and E is not a subclass of some class declared in the It is a compile-time error if a class variable initializer (§8.3.2) or static initializer (§8.7) of a named class or interface can throw a checked exception class. It is a compile-time error if an instance variable initializer
(§8.3.2) or instance initializer (§8.6) of a named class can throw a checked exception class, unless the named class has at least one explicitly declared constructor and the exception class or one of its
superclasses is explicitly declared in the Note that no compile-time error is due if an instance variable initializer or instance initializer of an anonymous class (§15.9.5) can throw an exception class. In a named class, it is the responsibility of the programmer to propagate information about which
exception classes can be thrown by initializers, by declaring a suitable It is a compile-time error if a It is a compile-time error if a A Java compiler is encouraged to issue a warning if a Example 11.2.3-1. Catching Checked Exceptions import java.io.*; class StaticallyThrownExceptionsIncludeSubtypes { public static void main(String[] args) { try { throw new FileNotFoundException(); } catch (IOException ioe) { // "catch IOException" catches IOException // and any subtype. } try { throw new FileNotFoundException(); // Statement "can throw" FileNotFoundException. // It is not the case that statement "can throw" // a subtype or supertype of FileNotFoundException. } catch (FileNotFoundException fnfe) { // ... Handle exception ... } catch (IOException ioe) { // Legal, but compilers are encouraged to give // warnings as of Java SE 7, because all subtypes of // IOException that the try block "can throw" have // already been caught by the prior catch clause. } try { m(); // m's declaration says "throws IOException", so // m "can throw" IOException. It is not the case // that m "can throw" a subtype or supertype of // IOException (e.g. Exception). } catch (FileNotFoundException fnfe) { // Legal, because the dynamic type of the exception // might be FileNotFoundException. } catch (IOException ioe) { // Legal, because the dynamic type of the exception // might be a different subtype of IOException. } catch (Throwable t) { // Can always catch Throwable. } } static void m() throws IOException { throw new FileNotFoundException(); } } By the rules above, each alternative in a multi- try { ... } catch (Foo f) { ... } catch (Bar | SubclassOfFoo e) { ... } 11.3. Run-Time Handling of an ExceptionWhen an exception is thrown (§14.18), control is transferred from the code
that caused the exception to the nearest dynamically enclosing A statement or expression is dynamically enclosed by a The caller of a statement or expression depends on where it occurs:
Whether a particular Equivalently, a The control transfer that occurs when an exception is thrown causes
abrupt completion of expressions (§15.6) and statements (§14.1) until a All exceptions (synchronous and asynchronous) are precise: when the transfer of control takes place, all effects of the statements executed and expressions evaluated before the point from which the exception is thrown must appear to have taken place. No expressions, statements, or parts thereof that occur after the point from which the exception is thrown may appear to have been evaluated. If optimized code has speculatively executed some of the expressions or statements which follow the point at which the exception occurs, such code must be prepared to hide this speculative execution from the user-visible state of the program. If no
In situations where it is desirable to ensure that one block of code is always executed after another, even if that other block of code completes abruptly, a If a If a The exact rules for abrupt completion and for the catching of exceptions are specified in detail with the specification of each statement in §14 (Blocks and Statements) and for expressions in §15 (Expressions) (especially §15.6). Example 11.3-1. Throwing and Catching Exceptions The following program declares an exception class class TestException extends Exception { TestException() { super(); } TestException(String s) { super(s); } } class Test { public static void main(String[] args) { for (String arg : args) { try { thrower(arg); System.out.println("Test \"" + arg + "\" didn't throw an exception"); } catch (Exception e) { System.out.println("Test \"" + arg + "\" threw a " + e.getClass() + "\n with message: " + e.getMessage()); } } } static int thrower(String s) throws TestException { try { if (s.equals("divide")) { int i = 0; return i/i; } if (s.equals("null")) { s = null; return s.length(); } if (s.equals("test")) { throw new TestException("Test message"); } return 0; } finally { System.out.println("[thrower(\"" + s + "\") done]"); } } } If we execute the program, passing it the arguments: divide null not test it produces the output: [thrower("divide") done] Test "divide" threw a class java.lang.ArithmeticException with message: / by zero [thrower("null") done] Test "null" threw a class java.lang.NullPointerException with message: null [thrower("not") done] Test "not" didn't throw an exception [thrower("test") done] Test "test" threw a class TestException with message: Test message The declaration of the method Notice that the When an exception is thrown by a method that is executing?8) When an exception is thrown by a method that is executing under several layers of method calls, a stack trace indicates the method executing when an exception occurred and all of the methods that were called in order to execute that method.
When you write a method that throws a checked exception you must?If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using the throws keyword. In checked exception, there are two types: fully checked and partially checked exceptions.
When the code in a try block may throw more than one type of exception you need to write a catch clause for each type of exception that could potentially be thrown?When the code in a try block may throw more than one type of exception, you need to write a catch clause for each type of exception that could potentially be thrown. All of the exceptions that you will handle are instances of classes that extend this class.
When catching multiple exceptions that are related to one another?When catching multiple exceptions that are related to one another through inheritance, you should handle the more specialized exception classes before the more general exception classes. To serialize an object and write it to the file, use this method of the ObjectOutputStream class.
|