Presentation is loading. Please wait.

Presentation is loading. Please wait.

Handling Exceptions.

Similar presentations


Presentation on theme: "Handling Exceptions."— Presentation transcript:

1 Handling Exceptions

2 Why Exceptions? Programmers tend to think they are invincible, which is ABSOLUTELY wrong. Recall we are humans. The ideal time to catch the error is at compile time. However, the real nasty errors occur during runtime. For programmers to handle runtime errors, Java provides so called exception handling. Underlying idea of exception handling in Java is: badly-formed code should not be run Instead of executing erroneous code, let the user know.

3 Exceptional Condition
An exceptional condition or situation is what prevents the continuation of program. It can be anything. User Input Error Device Error Physical Limitation Code Errors --- This is where most exceptions are thrown.

4 Throwing Exception A Java method can throw an Exception if it is facing bad situation it can not handle. Notice it is programmer who decide which exception to throw. Throws means returns an Exception to its caller. Exception is a class, which means we should create an instance of it using new keyword. if ( t == null ) throws new NullPointerException(); A method which may throw an exception should let compiler know its chance of throwing an exception. public string readLine() throws IOException

5 Exception Hierarchy Throwable Error Exception IOException
RuntimeException MalformedURLException NullPointerException

6 RumtimeException A RuntimeException occurs because of programming error, which may include: A bad cast (ClassCastException) An out-of-bound array access (ArrayIndexOutOfBoundsException) A null pointer access (NullPointerException) If you encounters a RuntimeException, It is completely your fault!!!. Generally, program will be terminated when a RuntimeException occurs. However, it leaves lots of useful information for debugging.

7 Advantages of Exception Handling
In C, we need to check return values of every function call for error handling. if ( read(buf,SIZE) == -1 ) This kind of error handling is very tedious, although necessary. In Java, we can designate separate exception handling region. You try to run a block of code, which may throw Exceptions. You catch the thrown exception in a designated area. This makes reading, writing, and debugging code becomes much clearer.

8 Context Every Java statement belongs to a context of certain level.
You can think the current context as the current scope. Or every {,} pair constitutes a context. A try/catch block forms a context since it is enclosed by a pair of {,}. Every called method forms a lower context and calling method forms higher context. void a() int b() { { int y = b(); return 3; } }

9 Context cont. Every method is returned by executing return keyword, which may physically return some value or not. Here, return means returning to the higher context. All these calling and returning sequences are processed via stack. Since stack is so important in many ways, it is covered briefly here.

10 Exception Handling At the point where the runtime error occurs, you probably do not know what to do. Only thing you do know is that the code should not continue on. Then, whose job is it to figure out what to do? Let’s consider this from the context point of view. try { URL url = new URL(“ }catch (MalformedURLException e) { // Handling should be here, where is the higher context. } URL() constructor does not know what to do when there is something wrong with input string. It is the higher context that should handle exception.

11 Catching any exception
It is possible to create a handler that catches any kind of exception. (This is possible due to the class hierarchy) Treat every possible exception as Exception, which is the base class that’s what programmers are most interested in. Three useful methods in Exception class. String getMessage() Gets the detailed message String toString() Overridden method from Object void printStackTrace() Prints out calling sequence in reverse order.

12 public class ExceptionDemo {
try { thrower(); } catch (Exception e) { System.out.println(“I got it!!!”); System.out.println(“message: “ + e.getMessage()); System.out.println(“more message: “ + e.toString()); e.printStackTrace(); } private void thrower() throws IOException { throw new Exception(“This is harmless exception”); public static void main(String args[]) { new ExceptionDemo();

13 Output Result I got it!!! message: This is harmless exception
more message: java.io.IOException: This is harmless exception java.io.IOException: This is harmless exception at ExceptionDemo.thrower(ExceptionDemo.java:17) at ExceptionDemo.<init>(ExceptionDemo.java:6) at ExceptionDemo.main(ExceptionDemo.java:21)

14 public class Runtime { Runtime() { thrower(); System.out.println("I will never reach here!"); } private void thrower() { throw new ArrayIndexOutOfBoundsException(); public static void main(String args[]) { new Runtime2();

15 Output Result Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException at Runtime2.thrower(Runtime2.java:10) at Runtime2.<init>(Runtime2.java:5) at Runtime2.main(Runtime2.java:14)

16 public class Runtime { Runtime() { try { thrower(); }catch (Exception e) { System.out.println("I got it!!!"); System.out.println("message: " + e.getMessage()); System.out.println("more message: " + e.toString()); e.printStackTrace(); } System.out.println(”I finally got here!!!"); private void thrower() { throw new ArrayIndexOutOfBoundsException(“This is a fake exception); public static void main(String args[]) { new Runtime();

17 Output Result I got it!!! message: This is a fake exception
more message: java.lang.ArrayIndexOutOfBoundsException: This is a fake exception java.lang.ArrayIndexOutOfBoundsException: This is a fake exception at Runtime.thrower(Runtime.java:15) at Runtime.<init>(Runtime.java:4) at Runtime.main(Runtime.java:19) I finally got here!!!


Download ppt "Handling Exceptions."

Similar presentations


Ads by Google