10.7 CHECKED AND UNCHECKED EXCEPTIONS IN JAVA


10.7 CHECKED AND UNCHECKED EXCEPTIONS IN JAVA

All of the Java exception handling examples we have shown so far deal with checked exceptions. For a checked exception, the compiler makes sure that your code makes provisions for either catching the exception or for re-throwing it.

Java also supports another kind of exceptions-unchecked exceptions-that are objects of type RuntimeException or of type Error. An unchecked exception is beyond the purview of the compiler, in the sense that the compiler will not insist that your program include exception handling code (meaning code to either catch the exception, or to re-throw the exception). However, if a method capable of throwing an unchecked exception actually ends up throwing the exception during program execution, the exception will be trapped by the runtime and will cause termination of the Java Virtual Machine unless, of course, your program catches the exception.

Unchecked exception of type Error usually indicate serious problems at run time; there is never a good reason for catching them. Here are some examples of system-defined exceptions that are of type Error: OutOf MemoryError, NoSuchMethod-Error, StackOverflowError, and so on.

Examples of system-defined exceptions of type RuntimeException include ArithmeticException, ClassCastException, IllegalArgumentException, NullPointerException, and so on.

Simply to illustrate that an exception of type RuntimeException does not have to be handled in the same manner as a checked exception, the following example shows a modified form of the code shown earlier in ExceptionUsage1. java:

 
//RuntimeExcep.java class MyException extends RuntimeException { //(A) public MyException() { super (); } public MyException(String s) { super (s); } } class Test { static void f () throws MyException { throw new MyException( "Exception thrown by function f()"); } public static void main(String[] args) { f(); //(B) } }

Comparing this program to the one in ExceptionUsage1. java, note that in line (A) we now extend RuntimeException as opposed to Exception. That allows us to call f() in line (B) without the try-catch block used in main of ExceptionUsage 1.java. If we compile and execute this code, the function f() will throw the designated exception which will be trapped by the runtime that will bring the program to a halt.




Programming With Objects[c] A Comparative Presentation of Object-Oriented Programming With C++ and Java
Programming with Objects: A Comparative Presentation of Object Oriented Programming with C++ and Java
ISBN: 0471268526
EAN: 2147483647
Year: 2005
Pages: 273
Authors: Avinash Kak

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net