{"id":3448,"date":"2019-06-20T11:43:42","date_gmt":"2019-06-20T11:43:42","guid":{"rendered":"http:\/\/softlect.in\/?p=3448"},"modified":"2019-06-20T12:02:07","modified_gmt":"2019-06-20T12:02:07","slug":"java-exception-handling","status":"publish","type":"post","link":"http:\/\/softlect.com\/index.php\/java-exception-handling\/","title":{"rendered":"Java Exception Handling"},"content":{"rendered":"<h1><a name=\"_Toc179309585\"><\/a><strong>Exception Handling<\/strong><\/h1>\n<p>&nbsp;<\/p>\n<p>An <em>exception <\/em>is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error. In computer languages that do not support exception handling, errors must be checked and handled manually typically through the use of error codes, and so on. This approach is as cumbersome as it is troublesome. Java\u2019s exception handling avoids these.<\/p>\n<p>&nbsp;<\/p>\n<h2><a name=\"_Toc179309586\"><\/a><strong>Exception-Handling Fundamentals<\/strong><\/h2>\n<p>A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code. When an exceptional condition arises, an object representing that exception is created and <em>thrown <\/em>in the method that caused the error. That method may choose to handle the exception itself, or pass it on. Either way, at some point, the exception is <em>caught <\/em>and processed. Exceptions can be generated by the Java run-time system, or they can be manually generated by your code. Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment. Java exception handling is managed via five keywords: <strong>try<\/strong>, <strong>catch<\/strong>, <strong>throw<\/strong>, <strong>throws<\/strong>, and <strong>finally<\/strong>. Briefly, here is how they work. Program statements that you want to monitor for exceptions are contained within a <strong>try <\/strong>block. If an exception occurs within the <strong>try <\/strong>block, it is thrown. Your code can catch this exception (using <strong>catch<\/strong>) and handle it in some manner. System-generated exceptions are automatically thrown by the Java run-time system. To manually throw an exception, use the keyword <strong>throw<\/strong>. Any exception that is thrown out of a method must be specified as such by a <strong>throws <\/strong>clause. Any code that absolutely must be executed before a method returns is put in a <strong>finally <\/strong>block. This is the general form of an exception-handling block:<\/p>\n<p>try {<\/p>\n<p>\/\/ block of code to monitor for errors<\/p>\n<p>}<\/p>\n<p>catch (<em>ExceptionType1 exOb<\/em>) {<\/p>\n<p>\/\/ exception handler for <em>ExceptionType1<\/em><\/p>\n<p>}<\/p>\n<p>catch (<em>ExceptionType2 exOb<\/em>) {<\/p>\n<p>\/\/ exception handler for <em>ExceptionType2<\/em><\/p>\n<p>}<\/p>\n<p>\/\/ &#8230;<\/p>\n<p>finally {<\/p>\n<p>\/\/ block of code to be executed before try block ends<\/p>\n<p>}<\/p>\n<p>Here, <em>ExceptionType <\/em>is the type of exception that has occurred. The remainder of this chapter describes how to apply this framework.<\/p>\n<p>&nbsp;<\/p>\n<h2><a name=\"_Toc179309587\"><\/a><strong>Exception Types<\/strong><\/h2>\n<p>All exception types are subclasses of the built-in class <strong>Throwable<\/strong>. Thus, <strong>Throwable <\/strong>is at the top of the exception class hierarchy. Immediately below <strong>Throwable <\/strong>are two subclasses that partition exceptions into two distinct branches. One branch is headed by <strong>Exception<\/strong>. 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. There is an important subclass of <strong>Exception<\/strong>, called <strong>RuntimeException<\/strong>. Exceptions of this type are automatically defined for the programs that you write and include things such as division by zero and invalid array indexing<\/p>\n<h3><a name=\"_Toc179309588\"><\/a>Uncaught Exceptions<\/h3>\n<p>Before you learn how to handle exceptions in your program, it is useful to see what happens when you don\u2019t handle them. This small program includes an expression that intentionally causes a divide-by-zero error.<\/p>\n<p>class Exc0 {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>int d = 0;<\/p>\n<p>int a = 42 \/ d;<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>When the Java run-time system detects the attempt to divide by zero, it constructs a new exception object and then <em>throws <\/em>this exception. This causes the execution of <strong>Exc0 <\/strong>to stop, because once an exception has been thrown, it must be <em>caught <\/em>by an exception handler and dealt with immediately. In this example, we haven\u2019t supplied any exception handlers of our own, so the exception is caught by the default handler provided by the Java run-time system. Any exception that is not caught by your program will ultimately be processed by the default handler. The default handler displays a string describing the exception, prints a stack trace from the point at which the exception occurred, and terminates the program. Here is the output generated when this example is executed.<\/p>\n<p>&nbsp;<\/p>\n<p>java.lang.ArithmeticException: \/ by zero<\/p>\n<p>at Exc0.main(Exc0.java:4)<\/p>\n<p>&nbsp;<\/p>\n<p>Notice how the class name, <strong>Exc0<\/strong>; the method name, <strong>main<\/strong>; the filename, <strong>Exc0.java<\/strong>; and the line number, <strong>4<\/strong>, are all included in the simple stack trace. Also, notice that the type of the exception thrown is a subclass of <strong>Exception <\/strong>called <strong>ArithmeticException<\/strong>, which more specifically describes what type of error happened. As discussed later in this chapter, Java supplies several built-in exception types that match the various sorts of run-time errors that can be generated. For example, here is another version of the preceding program that introduces the same error but in a method separate from <strong>main( )<\/strong>:<\/p>\n<p>class Exc1 {<\/p>\n<p>static void subroutine() {<\/p>\n<p>int d = 0;<\/p>\n<p>int a = 10 \/ d;<\/p>\n<p>}<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>Exc1.subroutine();<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>&nbsp;<\/p>\n<p>The resulting stack trace from the default exception handler shows how the entire call stack is displayed:<\/p>\n<p>&nbsp;<\/p>\n<p>java.lang.ArithmeticException: \/ by zero<\/p>\n<p>at Exc1.subroutine(Exc1.java:4)<\/p>\n<p>at Exc1.main(Exc1.java:7)<\/p>\n<p>&nbsp;<\/p>\n<p>As you can see, the bottom of the stack is <strong>main<\/strong>\u2019s line 7, which is the call to <strong>subroutine( )<\/strong>, which caused the exception at line 4. The call stack is quite useful for debugging, because it pinpoints the precise sequence of steps that led to the error.<\/p>\n<h3><a name=\"_Toc179309589\"><\/a>Using try and catch<\/h3>\n<p>Although the default exception handler provided by the Java run-time system is useful for debugging, you will usually want to handle an exception yourself. Doing so provides two benefits. First, it allows you to fix the error. Second, it prevents the program from automatically terminating. Most users would be confused (to say the least) if your program stopped running and printed a stack trace whenever an error occurred! Fortunately, it is quite easy to prevent this. To guard against and handle a run-time error, simply enclose the code that you want to monitor inside a <strong>try <\/strong>block. Immediately following the <strong>try <\/strong>block, include a <strong>catch <\/strong>clause that specifies the exception type that you wish to catch. To illustrate how easily this can be done, the following program includes a <strong>try <\/strong>block and a <strong>catch <\/strong>clause which processes the <strong>ArithmeticException <\/strong>generated by the division-by-zero error:<\/p>\n<p>&nbsp;<\/p>\n<p>class Exc2 {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>int d, a;<\/p>\n<p>try { \/\/ monitor a block of code.<\/p>\n<p>d = 0;<\/p>\n<p>a = 42 \/ d;<\/p>\n<p>System.out.println(&#8220;This will not be printed.&#8221;);<\/p>\n<p>} catch (ArithmeticException e) { \/\/ catch divide-by-zero error<\/p>\n<p>System.out.println(&#8220;Division by zero.&#8221;);<\/p>\n<p>}<\/p>\n<p>System.out.println(&#8220;After catch statement.&#8221;);<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>&nbsp;<\/p>\n<p>This program generates the following output:<\/p>\n<p>Division by zero.<\/p>\n<p>After catch statement.<\/p>\n<p>&nbsp;<\/p>\n<p>Notice that the call to <strong>println( ) <\/strong>inside the <strong>try <\/strong>block is never executed. Once an exception is thrown, program control transfers out of the <strong>try <\/strong>block into the <strong>catch <\/strong>block. Put differently, <strong>catch <\/strong>is not \u201ccalled,\u201d so execution never \u201creturns\u201d to the <strong>try <\/strong>block from a <strong>catch<\/strong>. Thus, the line \u201cThis will not be printed.\u201d is not displayed. Once the <strong>catch <\/strong>statement has executed, program control continues with the next line in the program following the entire <strong>try<\/strong>\/<strong>catch <\/strong>mechanism. A <strong>try <\/strong>and its <strong>catch <\/strong>statement form a unit. The scope of the <strong>catch <\/strong>clause is restricted to those statements specified by the immediately preceding <strong>try <\/strong>statement. A <strong>catch <\/strong>statement cannot catch an exception thrown by another <strong>try <\/strong>statement (except in the case of nested <strong>try <\/strong>statements, described shortly). The statements that are protected by <strong>try <\/strong>must be surrounded by curly braces. That is, they must be within a block. You cannot use <strong>try <\/strong>on a single statement. The goal of most well-constructed <strong>catch <\/strong>clauses should be to resolve the exceptional condition and then continue on as if the error had never happened. For example, in the next program each iteration of the <strong>for <\/strong>loop obtains two random integers. Those two integers are divided by each other, and the result is used to divide the value 12345. The final result is put into <strong>a<\/strong>. If either division operation causes a divide-by-zero error, it is caught, the value of <strong>a <\/strong>is set to zero, and the program continues.<\/p>\n<p>&nbsp;<\/p>\n<p>\/\/ Handle an exception and move on.<\/p>\n<p>import java.util.Random;<\/p>\n<p>class HandleError {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>int a=0, b=0, c=0;<\/p>\n<p>Random r = new Random();<\/p>\n<p>for(int i=0; i&lt;32000; i++) {<\/p>\n<p>try {<\/p>\n<p>b = r.nextInt();<\/p>\n<p>c = r.nextInt();<\/p>\n<p>a = 12345 \/ (b\/c);<\/p>\n<p>} catch (ArithmeticException e) {<\/p>\n<p>System.out.println(&#8220;Division by zero.&#8221;);<\/p>\n<p>a = 0; \/\/ set a to zero and continue<\/p>\n<p>}<\/p>\n<p>System.out.println(&#8220;a: &#8221; + a);<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<h3><a name=\"_Toc179309590\"><\/a>Displaying a Description of an Exception<\/h3>\n<p><strong>Throwable <\/strong>overrides the <strong>toString( ) <\/strong>method defined by <strong>Object<\/strong> so that it returns a string containing a description of the exception. You can display this description in a <strong>println( ) <\/strong>statement by simply passing the exception as an argument. For example, the <strong>catch <\/strong>block in the preceding program can be rewritten like this:<\/p>\n<p>&nbsp;<\/p>\n<p>catch (ArithmeticException e) {<\/p>\n<p>System.out.println(&#8220;Exception: &#8221; + e);<\/p>\n<p>a = 0; \/\/ set a to zero and continue<\/p>\n<p>}<\/p>\n<p>&nbsp;<\/p>\n<p>When this version is substituted in the program, and the program is run, each divide-by-zero error displays the following message:<\/p>\n<p>&nbsp;<\/p>\n<p>Exception: java.lang.ArithmeticException: \/ by zero<\/p>\n<p>&nbsp;<\/p>\n<p>While it is of no particular value in this context, the ability to display a description of an exception is valuable in other circumstances\u2014particularly when you are experimenting with exceptions or when you are debugging.<\/p>\n<p>&nbsp;<\/p>\n<h2><a name=\"_Toc179309591\"><\/a><strong>Multiple catch Clauses<\/strong><\/h2>\n<p>In some cases, more than one exception could be raised by a single piece of code. To handle this type of situation, you can specify two or more <strong>catch <\/strong>clauses, each catching a different type of exception. When an exception is thrown, each <strong>catch <\/strong>statement is inspected in order, and the first one whose type matches that of the exception is executed. After one <strong>catch <\/strong>statement executes, the others are bypassed, and execution continues after the <strong>try<\/strong>\/<strong>catch <\/strong>block. The following example traps two different exception types:<\/p>\n<p>&nbsp;<\/p>\n<p>\/\/ Demonstrate multiple catch statements.<\/p>\n<p>class MultiCatch {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>try {<\/p>\n<p>int a = args.length;<\/p>\n<p>System.out.println(&#8220;a = &#8221; + a);<\/p>\n<p>int b = 42 \/ a;<\/p>\n<p>int c[] = { 1 };<\/p>\n<p>c[42] = 99;<\/p>\n<p>} catch(ArithmeticException e) {<\/p>\n<p>System.out.println(&#8220;Divide by 0: &#8221; + e);<\/p>\n<p>} catch(ArrayIndexOutOfBoundsException e) {<\/p>\n<p>System.out.println(&#8220;Array index oob: &#8221; + e);<\/p>\n<p>}<\/p>\n<p>System.out.println(&#8220;After try\/catch blocks.&#8221;);<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>&nbsp;<\/p>\n<p>This program will cause a division-by-zero exception if it is started with no commandline parameters, since <strong>a <\/strong>will equal zero. It will survive the division if you provide a command-line argument, setting <strong>a <\/strong>to something larger than zero. But it will cause an <strong>ArrayIndexOutOfBoundsException<\/strong>, since the <strong>int <\/strong>array <strong>c <\/strong>has a length of 1, yet the program attempts to assign a value to <strong>c[42]<\/strong>. Here is the output generated by running it both ways:<\/p>\n<p>&nbsp;<\/p>\n<p>C:\\&gt;java MultiCatch<\/p>\n<p>a = 0<\/p>\n<p>Divide by 0: java.lang.ArithmeticException: \/ by zero<\/p>\n<p>After try\/catch blocks.<\/p>\n<p>C:\\&gt;java MultiCatch TestArg<\/p>\n<p>a = 1<\/p>\n<p>Array index oob: java.lang.ArrayIndexOutOfBoundsException<\/p>\n<p>After try\/catch blocks.<\/p>\n<p>&nbsp;<\/p>\n<p>When you use multiple <strong>catch <\/strong>statements, it is important to remember that exception subclasses must come before any of their superclasses. This is because a <strong>catch <\/strong>statement that uses a superclass will catch exceptions of that type plus any of its subclasses. Thus, a subclass would never be reached if it came after its superclass. Further, in Java, unreachable code is an error. For example, consider the following program:<\/p>\n<p>&nbsp;<\/p>\n<p>\/* This program contains an error.<\/p>\n<p>A subclass must come before its superclass in<\/p>\n<p>a series of catch statements. If not,<\/p>\n<p>unreachable code will be created and a<\/p>\n<p>compile-time error will result.<\/p>\n<p>*\/<\/p>\n<p>class SuperSubCatch {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>try {<\/p>\n<p>int a = 0;<\/p>\n<p>int b = 42 \/ a;<\/p>\n<p>} catch(Exception e) {<\/p>\n<p>System.out.println(&#8220;Generic Exception catch.&#8221;);<\/p>\n<p>}<\/p>\n<p>\/* This catch is never reached because<\/p>\n<p>ArithmeticException is a subclass of Exception. *\/<\/p>\n<p>catch(ArithmeticException e) { \/\/ ERROR &#8211; unreachable<\/p>\n<p>System.out.println(&#8220;This is never reached.&#8221;);<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>&nbsp;<\/p>\n<p>If you try to compile this program, you will receive an error message stating that the second <strong>catch <\/strong>statement is unreachable because the exception has already been caught. Since <strong>ArithmeticException <\/strong>is a subclass of <strong>Exception<\/strong>, the first <strong>catch <\/strong>statement will handle all <strong>Exception<\/strong>-based errors, including <strong>ArithmeticException<\/strong>. This means that the second <strong>catch <\/strong>statement will never execute. To fix the problem, reverse the order of the <strong>catch <\/strong>statements.<\/p>\n<p>&nbsp;<\/p>\n<h2><a name=\"_Toc179309592\"><\/a><strong>Nested try Statements<\/strong><\/h2>\n<p>The <strong>try <\/strong>statement can be nested. That is, a <strong>try <\/strong>statement can be inside the block of another <strong>try<\/strong>. Each time a <strong>try <\/strong>statement is entered, the context of that exception is pushed on the stack. If an inner <strong>try <\/strong>statement does not have a <strong>catch <\/strong>handler for a particular exception, the stack is unwound and the next <strong>try <\/strong>statement\u2019s <strong>catch <\/strong>handlers are inspected for a match. This continues until one of the <strong>catch <\/strong>statements succeeds, or until all of the nested <strong>try <\/strong>statements are exhausted. If no <strong>catch <\/strong>statement matches, then the Java run-time system will handle the exception. Here is an example that uses nested <strong>try <\/strong>statements:<\/p>\n<p>&nbsp;<\/p>\n<p>\/\/ An example of nested try statements.<\/p>\n<p>class NestTry {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>try {<\/p>\n<p>int a = args.length;<\/p>\n<p>\/* If no command-line args are present,<\/p>\n<p>the following statement will generate<\/p>\n<p>a divide-by-zero exception. *\/<\/p>\n<p>int b = 42 \/ a;<\/p>\n<p>System.out.println(&#8220;a = &#8221; + a);<\/p>\n<p>try { \/\/ nested try block<\/p>\n<p>\/* If one command-line arg is used,<\/p>\n<p>then a divide-by-zero exception<\/p>\n<p>will be generated by the following code. *\/<\/p>\n<p>if(a==1) a = a\/(a-a); \/\/ division by zero<\/p>\n<p>\/* If two command-line args are used,<\/p>\n<p>then generate an out-of-bounds exception. *\/<\/p>\n<p>if(a==2) {<\/p>\n<p>int c[] = { 1 };<\/p>\n<p>c[42] = 99; \/\/ generate an out-of-bounds exception<\/p>\n<p>}<\/p>\n<p>} catch(ArrayIndexOutOfBoundsException e) {<\/p>\n<p>System.out.println(&#8220;Array index out-of-bounds: &#8221; + e);<\/p>\n<p>}<\/p>\n<p>} catch(ArithmeticException e) {<\/p>\n<p>System.out.println(&#8220;Divide by 0: &#8221; + e);<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>&nbsp;<\/p>\n<p>As you can see, this program nests one <strong>try <\/strong>block within another. The program works as follows. When you execute the program with no command-line arguments, a divide-by-zero exception is generated by the outer <strong>try <\/strong>block. Execution of the program by one command-line argument generates a divide-by-zero exception from within the nested <strong>try <\/strong>block. Since the inner block does not catch this exception, it is passed on to the outer <strong>try <\/strong>block, where it is handled. If you execute the program with two command-line arguments, an array boundary exception is generated from within the inner <strong>try <\/strong>block. Here are sample runs that illustrate each case:<\/p>\n<p>&nbsp;<\/p>\n<p>C:\\&gt;java NestTry<\/p>\n<p>Divide by 0: java.lang.ArithmeticException: \/ by zero<\/p>\n<p>C:\\&gt;java NestTry One<\/p>\n<p>a = 1<\/p>\n<p>Divide by 0: java.lang.ArithmeticException: \/ by zero<\/p>\n<p>C:\\&gt;java NestTry One Two<\/p>\n<p>a = 2<\/p>\n<p>Array index out-of-bounds:<\/p>\n<p>java.lang.ArrayIndexOutOfBoundsException<\/p>\n<p>&nbsp;<\/p>\n<p>Nesting of <strong>try <\/strong>statements can occur in less obvious ways when method calls are involved. For example, you can enclose a call to a method within a <strong>try <\/strong>block. Inside that method is another <strong>try <\/strong>statement. In this case, the <strong>try <\/strong>within the method is still nested inside the outer <strong>try <\/strong>block, which calls the method. Here is the previous program recoded so that the nested <strong>try <\/strong>block is moved inside the method <strong>nesttry( )<\/strong>:<\/p>\n<p>&nbsp;<\/p>\n<p>\/* Try statements can be implicitly nested via<\/p>\n<p>calls to methods. *\/<\/p>\n<p>class MethNestTry {<\/p>\n<p>static void nesttry(int a) {<\/p>\n<p>try { \/\/ nested try block<\/p>\n<p>\/* If one command-line arg is used,<\/p>\n<p>then a divide-by-zero exception<\/p>\n<p>will be generated by the following code. *\/<\/p>\n<p>if(a==1) a = a\/(a-a); \/\/ division by zero<\/p>\n<p>\/* If two command-line args are used,<\/p>\n<p>then generate an out-of-bounds exception. *\/<\/p>\n<p>if(a==2) {<\/p>\n<p>int c[] = { 1 };<\/p>\n<p>c[42] = 99; \/\/ generate an out-of-bounds exception<\/p>\n<p>}<\/p>\n<p>} catch(ArrayIndexOutOfBoundsException e) {<\/p>\n<p>System.out.println(&#8220;Array index out-of-bounds: &#8221; + e);<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>try {<\/p>\n<p>int a = args.length;<\/p>\n<p>\/* If no command-line args are present,<\/p>\n<p>the following statement will generate<\/p>\n<p>a divide-by-zero exception. *\/<\/p>\n<p>int b = 42 \/ a;<\/p>\n<p>System.out.println(&#8220;a = &#8221; + a);<\/p>\n<p>nesttry(a);<\/p>\n<p>} catch(ArithmeticException e) {<\/p>\n<p>System.out.println(&#8220;Divide by 0: &#8221; + e);<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>The output of this program is identical to that of the preceding example.<\/p>\n<p>&nbsp;<\/p>\n<h2><a name=\"_Toc179309593\"><\/a><strong>finally<\/strong><\/h2>\n<p>When exceptions are thrown, execution in a method takes a rather abrupt, nonlinear path that alters the normal flow through the method. Depending upon how the method is coded, it is even possible for an exception to cause the method to return prematurely. This could be a problem in some methods. For example, if a method opens a file upon entry and closes it upon exit, then you will not want the code that closes the file to be bypassed by the exception-handling mechanism. The <strong>finally <\/strong>keyword is designed to address this contingency. <strong>finally <\/strong>creates a block of code that will be executed after a <strong>try<\/strong>\/<strong>catch <\/strong>block has completed and before the code following the <strong>try\/catch <\/strong>block. The <strong>finally <\/strong>block will execute whether or not an exception is thrown. If an exception is thrown, the <strong>finally <\/strong>block will execute even if no <strong>catch <\/strong>statement matches the exception. Any time a method is about to return to the caller from inside a <strong>try\/catch <\/strong>block, via an uncaught exception or an explicit return statement, the <strong>finally <\/strong>clause is also executed just before the method returns. This can be useful for closing file handles and freeing up any other resources that might have been allocated at the beginning of a method with the intent of disposing of them before returning. The <strong>finally <\/strong>clause is optional. However, each <strong>try <\/strong>statement requires at least one <strong>catch <\/strong>or a <strong>finally <\/strong>clause. Here is an example program that shows three methods that exit in various ways, none without executing their <strong>finally <\/strong>clauses:<\/p>\n<p>&nbsp;<\/p>\n<p>\/\/ Demonstrate finally.<\/p>\n<p>class FinallyDemo {<\/p>\n<p>\/\/ Through an exception out of the method.<\/p>\n<p>static void procA() {<\/p>\n<p>try {<\/p>\n<p>System.out.println(&#8220;inside procA&#8221;);<\/p>\n<p>throw new RuntimeException(&#8220;demo&#8221;);<\/p>\n<p>} finally {<\/p>\n<p>System.out.println(&#8220;procA&#8217;s finally&#8221;);<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>\/\/ Return from within a try block.<\/p>\n<p>static void procB() {<\/p>\n<p>try {<\/p>\n<p>System.out.println(&#8220;inside procB&#8221;);<\/p>\n<p>return;<\/p>\n<p>} finally {<\/p>\n<p>System.out.println(&#8220;procB&#8217;s finally&#8221;);<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>\/\/ Execute a try block normally.<\/p>\n<p>static void procC() {<\/p>\n<p>try {<\/p>\n<p>System.out.println(&#8220;inside procC&#8221;);<\/p>\n<p>} finally {<\/p>\n<p>System.out.println(&#8220;procC&#8217;s finally&#8221;);<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>try {<\/p>\n<p>procA();<\/p>\n<p>} catch (Exception e) {<\/p>\n<p>System.out.println(&#8220;Exception caught&#8221;);<\/p>\n<p>}<\/p>\n<p>procB();<\/p>\n<p>procC();<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>&nbsp;<\/p>\n<p>In this example, <strong>procA( ) <\/strong>prematurely breaks out of the <strong>try <\/strong>by throwing an exception. The <strong>finally <\/strong>clause is executed on the way out. <strong>procB( )<\/strong>\u2019s <strong>try <\/strong>statement is exited via a <strong>return <\/strong>statement. The <strong>finally <\/strong>clause is executed before <strong>procB( ) <\/strong>returns. In <strong>procC( )<\/strong>, the <strong>try <\/strong>statement executes normally, without error. However, the <strong>finally <\/strong>block is still executed. Here is the output generated by the preceding program:<\/p>\n<p>inside procA<\/p>\n<p>procA\u2019s finally<\/p>\n<p>Exception caught<\/p>\n<p>inside procB<\/p>\n<p>procB\u2019s finally<\/p>\n<p>inside procC<\/p>\n<p>procC\u2019s finally<\/p>\n<p>&nbsp;<\/p>\n<h2><a name=\"_Toc179309594\"><\/a><strong>Java\u2019s Built-in Exceptions<\/strong><\/h2>\n<p>Inside the standard package <strong>java.lang<\/strong>, Java defines several exception classes. A few have been used by the preceding examples. The most general of these exceptions are subclasses of the standard type <strong>RuntimeException<\/strong>. Since <strong>java.lang <\/strong>is implicitly imported into all Java programs, most exceptions derived from <strong>RuntimeException <\/strong>are automatically available. Furthermore, they need not be included in any method\u2019s <strong>throws <\/strong>list. In the language of Java, these are called <em>unchecked exceptions <\/em>because the compiler does not check to see if a method handles or throws these exceptions. The unchecked exceptions defined in <strong>java.lang <\/strong>are listed in Table 10-1. Table 10-2 lists those exceptions defined by <strong>java.lang <\/strong>that must be included in a method\u2019s <strong>throws <\/strong>list if that method can generate one of these exceptions and does not handle it itself. These are called <em>checked exceptions. <\/em>Java defines several other types of exceptions that relate to its various class libraries.<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Exception Handling &nbsp; An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error. In computer languages&hellip; <\/p>\n","protected":false},"author":1,"featured_media":3470,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[83],"tags":[],"aioseo_notices":[],"amp_enabled":true,"_links":{"self":[{"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/posts\/3448"}],"collection":[{"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/comments?post=3448"}],"version-history":[{"count":2,"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/posts\/3448\/revisions"}],"predecessor-version":[{"id":3487,"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/posts\/3448\/revisions\/3487"}],"wp:featuredmedia":[{"embeddable":true,"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/media\/3470"}],"wp:attachment":[{"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/media?parent=3448"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/categories?post=3448"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/tags?post=3448"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}