You are on page 1of 10

Chapter 8: Hephephep, here's an exceptional chapter...Exceptions and Assertions.

(3 hrs) Chapter Objectives: Identify the difference between Errors and Exceptions List the three (3) missions of exception handling. Introduce the try and catch keywords and explain when to use them. Explain the rules that governs the use of multiple catches. Introduce the use of the finally block. Decide when to use the handle and declare rule in exception handling. Explain the rules that governs overriding methods with declared exceptions Create your own exception. Introduce what are Assertions and its use. Demonstrate how to enable assertions during runtime for versions 1.4 and 5.0 and above What is an Exception? An exception is an abnormal condition that arises in a code sequence at run time. A Java exception is an object that describes an exceptional condition that has occurred in a piece of code. Exceptions can be generated in two ways: Java run-time system manually generated by your code. Why do we need to have Exception Handling? notify users save all work enable users to exit gracefully Mission of Error-Handling To transfer control from location of error to an error-handler designated to deal with the error. To make the user not be annoyed if the program ends abruptly. To avoid an abrupt conclusion due to the errors. Types of Problems User input error: e.g. syntactically incorrect URL, or correct URL but where web page no longer exists Device Errors: no paper in printer, serial port unavailable Physical limitations: disk full Code errors: wrong use of methods, invalid array index, popping an empty stack Sample Code: public class AddArgs1 { public static void main(String args[]) { int sum = 0; for (String arg : args) { sum += Integer.parseInt(arg); } System.out.println("Sum: " + sum); } } java AddArgs1 10 20 30 40 Sum: 100

Page 1 of 10

Prepared by: Lawrence G. Decamora III, scjp

java AddArgs1 10 2.2 thirty 40 Exception in thread "main" java.lang.NumberFormatException: For input string: "2.2" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at AddArgs1.main(AddArgs1.java:8) A stack trace will appear. A stack trace is an output that is a result of uncaught exceptions. It will tell the user information about the thrown exception. Try to look at the last line of the stack trace: at AddArgs1.main(AddArgs1.java:8),This means that the exception originated in line 8 of the source code AddArgs1.java in the main method. Exception Hierarchy in Java In Java, an exception is an instance of a class derived from Throwable.

Exception

The class Exception is used for exceptional conditions that user programs may catch. This is also the class that you will subclass to create your own custom exception types. RuntimeException is a subclass of class Exception. Exceptions of this type are automatically defined for the programs that your write and include things such as division by zero and invalid array indexing.

The Error Hierarchy The Error hierarchy describes internal errors and resource exhaustion inside the Java run-time system. The Error defines exceptions that are not expected to be caught under normal circumstances by your program. Objects of type Error are used by the Java run-time system to indicate errors having to do with the run-time environment itself. Stack overflow is an example of such an error. Stack overflow is usually caused by calling a method and not properly terminated.

Page 2 of 10

Prepared by: Lawrence G. Decamora III, scjp

Two branches of the Exception hierarchy 1. Unchecked Exceptiions - Exceptions that inherit from RuntimeException: caused by a programming error Rule of thumb: If it is a RuntimeException it is your fault! Examples

bad cast out-of-bounds array access ArrayIndexOutOfBoundsException null pointer access NullPointerException

2. Checked Exceptions - Exceptions that does not inherit from RuntimeException For example, an I/O error happens to a good program when trying to read past the end of file opening a malformed URL searching for a class object for a string that does not denote an existing class Uncaught Exceptions Enter your name: Bob<press enter key> Enter value for grade1: 90<press enter key> Enter value for grade2: 80a<press enter key> Exception in thread main java.lang.NumberFormatException: 80a at java.lang.Integer.parseInt(Compiled code) at java.lang.Integer.parseInt(Integer.java : 458) at Echoed.main(Echoed.java : 15) Javas Approach If a method is unable to complete the task in the usual way, Java allows it an alternative exit route: it does not seek to return a value, instead it throws an object encapsulating the error information. Java then begins a search for a handler that can deal with that error. The five keywords used for Exception handling or declaration try catch throw throws finally General form of an exception-handling block try { // block of code to monitor for errors or statements that might cause an exception } catch(ExceptionType1 exOb) { // exception handler for ExceptionType1 or what to do about it } catch(ExceptionType2 exOb) { // exception handler for ExceptionType2 }

Page 3 of 10

Prepared by: Lawrence G. Decamora III, scjp

// finally { //block of code to be executed before try block ends or statements here execute even if no Exception occurred } Using try and catch The default handler is useful for debugging. You can handle the exception by yourself. In doing so, there are two benefits: it allows you to fix the exception it prevents the program from automatically terminating Steps in guarding and handling the run-time error:
simply enclose the code that you want to monitor inside a try block immediately following the try block, include a catch clause that specifies the exception type that you wish to catch.

Sample program class Exc2 { public static void main(String args [] ) { int d, a; try { // monitor a block of code. d = 0; a = 42 / d; System.out.println(This will not be printed.); } catch (ArithmeticException e) { //catch divide-by-zero error System.out.println(Division by zero.); } System.out.println(After catch statement.); } } Output: Division by zero. After catch statement. Notice that the call to println() inside the try block is never executed. Once an exception is thrown, the program control transfers out of the try block into the catch block. Once the catch statement has executed, program control continues with the next line in the program following the entire try/catch mechanism.

Page 4 of 10

Prepared by: Lawrence G. Decamora III, scjp

Displaying a description of an Exception class Exc2 { public static void main(String args[]) { int d, a; try { // monitor a block of code. d = 0; a = 42 / d; System.out.println(This will not be printed.); } // end try block catch (ArithmeticException e) { //catch divide-by-zero error System.out.println(Exception: + e); }// end catch block System.out.println(After catch statement.); } // end of main } // end of class Output: Exception: java.lang.ArithmeticException: / by zero After catch statement. There are also instances that there can be a single try block and a series of catch blocks be included in a single code. Multiple catch Clauses int[] array = {22,23,0}; try { // monitor a block of code. d = 0; b = array[4]; a = 42 / d; System.out.println(This will not be printed.); } catch (ArithmeticException e) { //catch divide-by-zero error System.out.println(Division by zero.); } catch (IndexOutOfBoundsException e) { System.out.println(Invalid number); } System.out.println(After catch statement.); The Generic Exception (Exception Class) class Exc2 { public static void main(String args[] )

Page 5 of 10

Prepared by: Lawrence G. Decamora III, scjp

This catch is never reached int d, a; because ArithmeticException is a try subclass of Exception. { // monitor a block of code. d = 0; a = 42 / d; System.out.println(This will not be printed.); } catch (Exception e) { System.out.println(Generic Exception catch.); } catch (ArithmeticException e) { // ERROR - unreachable System.out.println(This is never reached.); } System.out.println(After catch statement.);

Nested try statements class NestTry { public static void main(String args[]) { try { int a = args.length; /* If no command-line args are present the following statement will generate a divide-by-zero exception.*/ int b = 42 / a; System.out.println(a = + a); try { // nested try block /* If one command-line arg is used, then a divide-by-zero exception will be generated by the following code. */ if(a==1) a = a / (a-a); // division by zero /* if two command-line args are used, then generate a number format exception. */ if(a ==2) a = a[4]; //index out of bounds } catch (IndexOutOfBoundsException e) { System.out.println(NumberFormatException: + e); } } catch (ArithmeticException e) { System.out.println(Divide by 0: + e); } }//main }//class

Page 6 of 10

Prepared by: Lawrence G. Decamora III, scjp

Output: C:\>java Nestry Divide by 0: java.lang.ArithmeticException: / by zero C:\>java Nestry One a = 1 Divide by 0: java.lang.ArithmeticException: / by zero C:\>java Nestry One Two a = 2 Number Format Exception: java.lang.NumberFormatException Two ways on how to deal with Exceptions. 1. Handle Rule

use try-catch-finally block for this. If an exception occurs within the try block, the catch block is there to handle it.

1. Declare Rule use the throws keyword for this. Declaring an exception is like issuing a waiver, if an exception occurs an abnormal termination will still happen. Declaring an exception lets the programmers do an immediate test on the code without worrying for the exact type of exception during the development stage. You can declare as many exceptions as you want. Syntax: throws IOException, SQLException, Exception Example of a Declared Exception import java.io.*; public class DeclaredException { public static void main(String args[]) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.println("What is your name?"); String name = in.readLine(); System.out.println("How old are you?"); int age = Integer.parseInt(in.readLine()); System.out.println("Hello " + name + ", next year you will be " + (age + 1) + " years old."); in.close(); } }

Page 7 of 10

Prepared by: Lawrence G. Decamora III, scjp

Create your own Exception To create your own Exception object, just extend the class Exception. class BadTastingFoodException extends Exception // put code here } With this example, you have just created a new Exception type called BadTastingFoodException. Now, let's put it to use. class BadTastingFoodException extends Exception {} public class MyOwnException { private static boolean candy = false; private static boolean sourBall = true; public static void main(String args[]) { try { System.out.println("Inside try block of candy."); isSour(candy); } catch(BadTastingFoodException btfe) { System.out.println("Inside catch block of candy."); } try { System.out.println("Inside try block of sourBall."); isSour(sourBall); } catch(BadTastingFoodException btfe) { System.out.println("Inside catch block of sourBall."); } } private static void isSour(boolean taste) throws BadTastingFoodException { if (taste) throw new BadTastingFoodException(); } } Sample Output: java MyOwnException Inside try block of candy. Inside try block of sourBall. Inside catch block of sourBall. Assertions Assertions checks the programmer's assumptions. Assertion checks can be programmatically placed in codes, but can be enabled or disabled during runtime. There are two ways on how to use assertion checking. {

Page 8 of 10

Prepared by: Lawrence G. Decamora III, scjp

Syntax: assert <boolean_expression> ; assert <boolean_expression> : <detail_expression> ; If you want to customize the displayed message, you can customize the <detail_expression> part. If the <boolean_expression> returns a false value, it will throw an AssertionError. Here's a sample code. public class TestAssert { public static void main(String args[]) { int hour = Integer.parseInt(args[0]); int mins = Integer.parseInt(args[1]); assert(hour > 0 && hour < 24) : "Invalid hour value"; assert(mins > 0 && mins < 60) : "Invalid mins value"; System.out.println(hour + ":" + mins); } }

Sample Output: java TestAssert 15 30 15:30 here's another one. java TestAssert 15 300 15:300 whoo...what a second, there's an inconsistency here. How did we have a correct and running program here? Java version 1.4 will has a different behavior compared to Java 1.5 and 1.6. Compile Time Java 1.4 javac -source 1.4 Filename.java Runtime Default behavior: enabled to disable: java -da Filename Default behavior: disabled to enable: java -ea Filename

Java 1.5 and 1.6 java Filename.java

In the last runtime example that we did, probably we are using a Java Runtime Environment that is 1.5 and above. So it means that during program execution or runtime, the assertion checking is disabled from your code. Thus ignoring the assertion check. You may want to rerun your application this way: java -ea TestAssert 15 300 Exception in thread "main" java.lang.AssertionError: Invalid mins value at TestAssert.main(TestAssert.java:9)

Page 9 of 10

Prepared by: Lawrence G. Decamora III, scjp

By putting -ea or -enableassertions, as a VM(Virtual Machine) option, your actually enabling the assertion check on your application at runtime. Also, you need to take note, that the error message states that it is an AssertionError and not an Exception, therefore you need to recheck or revalidate either your condition or your assumptions or your inputs.

Page 10 of 10

Prepared by: Lawrence G. Decamora III, scjp

You might also like