1 / 42

Java Programming Exception

Java Programming Exception. chojo@dju.ac.kr. SCJP 1.5 objectives. Declarations and Access Control Object Orientation Assignments Operators Flow Control, Exceptions , and Assertions Strings, I/O, Formatting, and Parsing Generics and Collections Inner Classes Threads Development.

melia
Download Presentation

Java Programming Exception

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java ProgrammingException chojo@dju.ac.kr

  2. SCJP 1.5 objectives • Declarations and Access Control • Object Orientation • Assignments • Operators • Flow Control,Exceptions, and Assertions • Strings, I/O, Formatting, and Parsing • Generics and Collections • Inner Classes • Threads • Development

  3. Contents What Is an Exception? The Catch or Specify Requirement Catching and Handling Exceptions Propagating Uncaught Exceptions The finally Block Exception Matching Specifying the Exceptions Thrown by a Method FOR SCJP EXAM Summary

  4. 1. What Is an Exception? Definition:  An exception is an event, which is an occurrence that alerts the normal program flow. The term exception is shorthand for the phrase "exceptional event.“ When an exceptional event occurs in java, an exception is said to be “thrown”. The code that’s responsible for doing something about the exception is called an “exception handler” and it “catches” the thrown exception.

  5. 2. The Catch or Specify Requirement • try : define a block of code in which exceptions may occur. • catch : match a specific exception to block of code that handles it. Ex:  if you call a method that opens a file but the file cannot be opened, execution of that method will stop, and code that you wrote to deal with this situation will be run. Therefore, we need a way to tell the JVM what code to execute when a certain exception happens.

  6. psedocode • try { • // This is the first line of the “guarded region” • //that is governed by the try keyword. • //Put code here that might cause some kind of exception. • //We may have many code lines here or just one • } • catch (FirstException){ • // Put code here that handles this exception. • // This is the next line of the exception handler. • } • catch (SecondException){ • // Put code here that handles this exception. • // This is the next line of the exception handler. • } • // Some code here that handles this exception.

  7. psedocode try { // do stuff }catch (SomeException ex){ // do exception handling }finally { // clean up } try { // do stuff } System.out.println(“out of try block”); try { // do stuff } System.out.println(“out of try block”); catch( Exception ex){ } try { // do stuff }finally { // clean up } It is illegal to use a try clause without either a catch clause or a finally clause. Any catch clauses must immediately follow the try block. Any finally clause must immediately follow the last catch clause.

  8. The Three Kinds of Exceptions unchecked exception • Not all exceptions are subject to the Catch (or Specify Requirement). • To understand why, we need to look at the three basic categories of exceptions, only one of which is subject to the Requirement. • The Three Kinds of Exceptions • checked exception • error • runtime exception

  9. Exception Hierarchy Java.lang.Object Java.lang.Throwable Java.lang.Error Java.lang.Exception Java.lang.RuntimeException CheckedException

  10. Example publicclass ArrayEx { publicstaticvoid main( String[] args ) { int[] intArray = newint[3]; for( int i=0 ; i<3 ; i++ ) { intArray[i] = i; } intArray[3] = 3; for( int i=0 ; i<intArray.length ; i++ ) { System.out.println( intArray[i] ); } } }

  11. 3. Catching and Handling Exceptions This section describes how to use the three exception handler components — the try, catch, and finally blocks — to write an exception handler.

  12. publicclass ArrayEx { publicstaticvoid main( String[] args ) { int[] intArray = newint[3]; for( int i=0 ; i<3 ; i++ ) { intArray[i] = i; } try{ intArray[3] = 3; } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Caught " + "ArrayIndexOutOfBoundsException: " ); } for( int i=0 ; i<intArray.length ; i++ ) { System.out.println( intArray[i] ); } } }

  13. Exception handlers can do more than just print error messages or halt the program. • They can do error recovery, prompt the user to make a decision, or propagate the error up to a higher-level handler using chained exceptions

  14. 4. Propagating Uncaught Exceptions • What happen to an exception that’s thrown in a try block when there is no catch clause waiting for it? • If a method doesn’t provide a catch clause for a particular exception, that method is said to be “ducking” the exception (or “passing the buck”).

  15. Java method call stack • 1) The call stack while method3() is running. The order in which methods are put on the call stack Ex:  If your program stats in method main() and main() calls method a(), which calls method b(), which in turn calls method c(), the call stack consists of the {c} , {b} , {a}, {main}.

  16. 2) The call stack after method3() completes Execution returns to method2() The order in which methods complete

  17. 5. The finally Block The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

  18. psedocode • try { • // This is the first line of the “guarded region” • } • catch (FirstException){ • // Put code here that handles this exception. • } • catch (SecondException){ • // Put code here that handles this exception. • } • finally { • // Put code here to release any resource • // we allocated in the try clause. • // More code here

  19. publicclass Human { String state = “human"; publicvoid state() { System.out.println( “I am human." ); } } publicclass Man extends Human { String name = “shine"; // return the variable, name public String getName() { return name; } // method overriding publicvoid state() { System.out.println( name + “is a man" ); } } publicclass Woman extends Human { String name = “chojo"; // return the variable, name public String getName() { return name; } // method overriding publicvoid state() { System.out.println( name + “is a woman" ); } }

  20. publicclass ClassCast { publicstaticvoid main( String[] args ) { // create Woman object Woman gemini = new Woman(); // Polymorphism Human wo = new Woman(); // call method to return name System.out.println( gemini.getName() ); String wName = ((Woman)wo).getName(); System.out.println( wName ); // classcasting //Man john = (Man)gemini; Man john = (Man)wo; // print name String mName = john.getName(); System.out.println( mName ); } }

  21. publicclass ClassCastHandling { publicstaticvoid main( String[] args ) { Woman gemini = new Woman(); Human wo = new Woman(); // call method to return name System.out.println( gemini.getName() ); String wName = ((Woman)wo).getName(); System.out.println( wName ); // class casting //Man john = (Man)gemini; try { Man john = (Man)wo; // print names String mName = john.getName(); System.out.println( mName ); } catch ( ClassCastException cc ) { //System.out.println( "Message1 : " + cc.getMessage() ); //cc.printStackTrace(); System.out.println( "Message2 : " + cc.toString() ); } finally { System.out.println( “A man cannot be a woman" ); } } }

  22. 6. Exception Matching • When an exception is thrown, Java will try to find a catch clause for the exception type. • If it doesn’t find one, it will search for a handler for a supertype of the exception. • If it doesn’t find a catch clause for supertype for the exception, then the exception is propagated down the call stack.

  23. publicclass MultiException { publicstaticvoid main( String[] args ) { int value = 20; int div = 0; int[] intArray = { 1, 2, 3 }; String s = null; int result = value / div; System.out.println( result ); int arrayValue = intArray[4]; System.out.println( arrayValue ); String newString = s.substring( 1, 4 ); System.out.println( newString ); } }

  24. publicclass MultiExceptionHandling { publicstaticvoid main( String[] args ) { int value = 20; int div = 0; int[] intArray = { 1, 2, 3 }; String s = null; try { int result = value / div; System.out.println( result ); int arrayValue = intArray[4]; System.out.println( arrayValue ); String newString = s.substring( 1, 4 ); System.out.println( newString ); } catch ( ArithmeticException ae ) { System.out.println( ae.toString() ); } catch ( ArrayIndexOutOfBoundsException ai ) { ai.printStackTrace(); } catch ( NullPointerException ne ) { System.out.println( ne.getMessage() ); }} }

  25. Resist the temptation to write a single catchall exception handler such as the following: try { // some code }catch (Exception e) { e.printStackTrace(); } This code will catch every exception generated. Of course, no single exception handler can properly handle every exception, and programming in this way defeats the design objective. Exception handlers that trap many errors at once will probably reduce the reliability of your program because it's likely that an exception will be caught that the handler does not know how to handle.

  26. import java.io.*; public class ReadData { public static void main(String args[]) { try { RandomAccessFile raf = new RandomAccessFile("myfile.txt", "r"); byte b[] = new byte[1000]; raf.readFully(b, 0, 1000); }catch (FileNotFoundException e) { System.err.println("File not found"); System.err.println(e.getMessage()); e.printStackTrace(); }catch (IOException e) { System.err.println("IO Error"); System.err.println(e.toString()); e.printStackTrace(); } } }

  27. Notice that the catch clause for the FileNotFoundException was placed above the handler for the IOException. This is really important! If we do it the opposite way, the program will not compile. try { // do risky IO things } catch (IOException e) { // handle general IOExceptions } catch (FileNotFoundException ex) { // handle just FileNotFoundException }

  28. 7.Specifying the Exceptions Thrown by a Method The previous section : how to write an exception handler In other cases, however, it's better to let a method further up the call stack handle the exception. The list of thrown exceptions is part of a method's public interface. The throws keyword is used as follows to list the exceptions that a method can throw: void myFunction() throws MyException1, MyException2 { // code for the method here }

  29. publicclass ThrowsException { publicvoid occurException() throws ArithmeticException { int result = 3/0; System.out.println( result ); } publicstaticvoid main( String[] args ) { ThrowException te = new ThrowException(); te.occurException(); } }

  30. public class ThrowsExceptionHandling { public void occurException() throws ArithmeticException { int result = 3/0; System.out.println( result ); } public static void main( String[] args ) { ThrowsExceptionHandling1 te = new ThrowsExceptionHandling1(); try { te.occurException(); } catch ( ArithmeticException ae ) { System.out.println( "Exception happens: " + ae.toString() ); System.out.println( “cannot divide by 0" ); } } } 1 2 3

  31. public class ThrowsExceptionHandling2 { public void occurException() throws ArithmeticException { int result = 3/0; System.out.println( result ); } public static void main( String[] args ) throws ArithmeticException { ThrowsExceptionHandling2 te = new ThrowsExceptionHandling2(); te.occurException(); } } 1 2 4 3 JVM

  32. publicclass ThrowException { publicvoid exceptionMethod() throws ArrayIndexOutOfBoundsException { int[] intA = { 1, 2, 3, 4 }; for( int i=0 ; i<10 ; i++ ) { if( i == 4 ) thrownew ArrayIndexOutOfBoundsException(); System.out.println( intA[i] ); }} publicstaticvoid main( String[] args ) { ThrowException te = new ThrowException(); try { te.exceptionMethod(); } catch ( ArrayIndexOutOfBoundsException ab ) { System.out.println( “overflow the index” ); ab.printStackTrace(); }}}

  33. RuntimeException • Suppose your method doesn't directly throw an exception, but calls a method that does. • You can choose not to handle the exception yourself and instead just declare it, as though it were your method that actually throws the exception. • If you do declare the exception that your method might get from another method, and you don't provide a try/catch for it, then the method will propagate back to the method that called your method, and either be caught there or continue on to be handled by a method further down the stack. • RuntimeException subclasses are exempt, so the compiler won't check to see if you've declared them. • But all non-RuntimeExceptions are considered "checked" exceptions.

  34. FOR SCJP EXAM

  35. int value = 20; int div = 0; int[] intArray = { 1, 2, 3 }; String s = null; int result = value / div; System.out.println( result ); int arrayValue = intArray[4]; System.out.println( arrayValue ); String newString = s.substring( 1, 4 ); System.out.println( newString );

  36. Common Exceptions and Errors • Understand which of these are thrown by the virtual machine and recognize situations in which others should be thrown programmatically. ArrayIndexOutOfBoundsException, ClassCastException, IllegalArgumentException, IllegalStateException, NullPointerException, NumberFormatException, AssertionError, ExceptionInInitializerError, StackOverflowError, or NoClassDefFoundError.

  37. Where Exceptions Come From • JVM exceptions • Those exceptions or errors that are either exclusively or most logically thrown by the JVM. • Programmatic exceptions • Those exceptions that are thrown explicitly by application and/or API programmers.

  38. A Summary of the Exam's Exceptions and Errors

  39. A Summary of the Exam's Exceptions and Errors

  40. Exercise • Make exception handling code • Case1 : j =0 • Case2 : i or j - not a number • Case3 : num of the parameter is not 2 • class ArgDiv { • public static void main(String args[]) { • System.out.println("Input 2 numbers"); • int i = Integer.parseInt(args[0]); • int j = Integer.parseInt(args[1]); • System.out.println("Division result = " + i/j); • } • }

  41. Summary • A program can use exceptions to indicate that an error occurred. To throw an exception, use the throw statement and provide it with an exception object — a descendant of Throwable — to provide information about the specific error that occurred. A method that throws an uncaught, checked exception must include a throws clause in its declaration. A program can catch exceptions by using a combination of the try, catch, and finally blocks. • The try block identifies a block of code in which an exception can occur. • The catch block identifies a block of code, known as an exception handler, that can handle a particular type of exception. • The finally block identifies a block of code that is guaranteed to execute, and is the right place to close files, recover resources, and otherwise clean up after the code enclosed in the try block. • The try statement should contain at least one catch block or a finally block and may have multiple catch blocks. • The class of the exception object indicates the type of exception thrown. The exception object can contain further information about the error, including an error message. With exception chaining, an exception can point to the exception that caused it, which can in turn point to the exception that caused it, and so on.

More Related