Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Programming Exception SCJP 1.5 objectives  Declarations and Access Control  Object Orientation  Assignments  Operators  Flow.

Similar presentations


Presentation on theme: "Java Programming Exception SCJP 1.5 objectives  Declarations and Access Control  Object Orientation  Assignments  Operators  Flow."— Presentation transcript:

1

2 Java Programming Exception

3 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

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

5 1. What Is an Exception?  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. Definition: An exception is an event, which is an occurrence that alerts the normal program flow.

6 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. 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.

7 psedocode 1.try { 2. // This is the first line of the “guarded region” 3. //that is governed by the try keyword. 4. //Put code here that might cause some kind of exception. 5. //We may have many code lines here or just one 6.} 7.catch (FirstException){ 8. // Put code here that handles this exception. 9. // This is the next line of the exception handler. 10. } 11.catch (SecondException){ 12. // Put code here that handles this exception. 13. // This is the next line of the exception handler. 14. } 15. // Some code here that handles this exception.

8 psedocode try { // do stuff }finally { // clean up } 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){ } 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.

9 The Three Kinds of Exceptions  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 1.checked exception 2.error 3.runtime exception unchecked exception

10 Exception Hierarchy Java.lang.Object Java.lang.Throwable Java.lang.ErrorJava.lang.Exception Java.lang.RuntimeException CheckedException

11 Example public class ArrayEx { public static void main( String[] args ) { int[] intArray = new int[3]; for( int i=0 ; i<3 ; i++ ) { intArray[i] = i; } intArray[3] = 3; for( int i=0 ; i

12 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.

13 public class ArrayEx { public static void main( String[] args ) { int[] intArray = new int[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

14  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

15 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”).

16 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}. method3() method2() method1() main() method2 invokes method3 method1 invokes method2 main invokes method1 main begins

17  2) The call stack after method3() completes Execution returns to method2() The order in which methods complete method2() method1() main() method2() will complete method1() will complete main() will complete and the JVM will exit

18 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.

19 psedocode 1.try { 2. // This is the first line of the “guarded region” 3.} 4.catch (FirstException){ 5. // Put code here that handles this exception. 6.} 7.catch (SecondException){ 8. // Put code here that handles this exception. 9.} 10.finally { 11. // Put code here to release any resource 12. // we allocated in the try clause. 13. // More code here

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

21 public class ClassCast { public static void 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 ); // class casting //Man john = (Man)gemini; Man john = (Man)wo; // print name String mName = john.getName(); System.out.println( mName ); }

22 public class ClassCastHandling { public static void 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" ); }} }

23

24 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.

25 public class MultiException { public static void 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 ); }

26 public class MultiExceptionHandling { public static void 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() ); }} }

27 try { // some code }catch (Exception e) { e.printStackTrace(); }  Resist the temptation to write a single catchall exception handler such as the following: 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.

28 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(); }

29  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 }

30 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 }

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

32 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

33 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(); } JVM

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

35 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.

36 FOR SCJP EXAM

37 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 );

38 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.

39 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.

40 A Summary of the Exam's Exceptions and Errors ExceptionDescription Typically Thrown ArrayIndexOutOfBounds Exception Thrown when attempting to access an array with an invalid index value (either negative or beyond the length of the array). By the JVM ClassCastException Thrown when attempting to cast a reference variable to a type that fails the IS-A test. By the JVM NullPointerException Thrown when attempting to access an object with a reference variable whose current value is null. By the JVM ExceptionInInitializerError Thrown when attempting to initialize a static variable or an initialization block. By the JVM StackOverflowError Typically thrown when a method recurses too deeply. (Each invocation is added to the stack.) By the JVM NoClassDefFoundError Thrown when the JVM can’t find a class it needs, because of a command-line error, a classpath issue, or a missing.class file. By the JVM

41 A Summary of the Exam's Exceptions and Errors ExceptionDescription Typically Thrown IllegalArgument Exception Thrown when a method receives an argument fo rmatted differently than the method expects. Programmat ically IllegalStateException Thrown when the state of the environment doesn ’t match the operation being attempted, e.g., usin g a Scanner that’s been closed. Programmat ically NumberFormat Exception Thrown when a method that converts a String to a number receives a String that it cannot convert. Programmat ically AssertionError Thrown when a statement’s boolean test returns false. Programmati cally

42 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); }

43 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. 1.The try block identifies a block of code in which an exception can occur. 2.The catch block identifies a block of code, known as an exception handler, that can handle a particular type of exception. 3.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.


Download ppt "Java Programming Exception SCJP 1.5 objectives  Declarations and Access Control  Object Orientation  Assignments  Operators  Flow."

Similar presentations


Ads by Google