1 / 30

JAVA Programcılığı 1.2.2

JAVA Programcılığı 1.2.2. Ali R+ SARAL. Ders Planı 1.2.2. Chapter 7 Exceptions Dealing with Exceptions Handling Exceptions The try Block The catch Block The finally Block. Ders Planı 1.2.2. Structuring a Method Execution Sequence Nested try Blocks Rethrowing Exceptions

lars-barton
Download Presentation

JAVA Programcılığı 1.2.2

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 Programcılığı 1.2.2 Ali R+ SARAL

  2. Ders Planı 1.2.2 • Chapter 7 Exceptions • Dealing with Exceptions • Handling Exceptions • The try Block • The catch Block • The finally Block

  3. Ders Planı 1.2.2 • Structuring a Method • Execution Sequence • Nested try Blocks • Rethrowing Exceptions • Exception Objects • Standard Exceptions • Defining Your Own Exceptions

  4. Exceptions • The Idea Behind Exceptions • One major benefit of having an error signaled by an exception is that it separates the code that deals with errors from the code that is executed when things are moving along smoothly. Another positive aspect of exceptions is that they provide a way of enforcing a response to particular errors.

  5. Types of Exceptions • Error Exceptions • RuntimeException Exceptions • Other Subclasses of Exception

  6. Types of Exceptions • Code or data errors you try to use an array index that’s outside the limits for the array, or an integer arithmetic expression has a zero divisor. • Standard method For example, if you use the substring() method in the String exceptions class, it can throw a StringIndexOutOfBoundsException exception. • Throwing your own You’ll see later in this chapter how you can throw a few of your exceptions own when you need to. • Java errors These can be due to errors in executing the Java Virtual Machine, which runs your compiled program, but usually arise as a consequence of an error in your program.

  7. Error Exceptions • ThreadDeath • LinkageError • VirtualMachineError

  8. RunTime Exceptions • ArithmeticException • IndexOutOfBoundsException • NegativeArraySizeException • NullPointerException • ArrayStoreException • ClassCastException • IllegalArgumentException

  9. RunTime Exceptions • SecurityException • IllegalMonitorStateException • IllegalStateException • UnsupportedOperationException

  10. Dealing with Exceptions • Specifying the Exceptions a Method Can Throw • double myMethod() throws IOException, FileNotFoundException { • // Detail of the method code... • }

  11. Dealing with Exceptions • Handling Exceptions • A try block encloses code that may give rise to one or more exceptions. Code that can throw an exception that you want to catch must be in a try block. • A catch block encloses code that is intended to handle exceptions of a particular type that may be thrown in the associated try block. I’ll get to how a catch block is associated with a try block in a moment. • The code in a finally block is always executed before the method ends, regardless of whether any exceptions are thrown in the try block.

  12. The try Block 1 EXAMPLE – TestTryCatch 01 UsingTryCatch • public class TestTryCatch { public static void main(String[] args) { int i = 1; int j = 0; try { System.out.println(“Try block entered “ + “i = “+ i + “ j = “+j); System.out.println(i/j); // Divide by 0 - exception thrown System.out.println(“Ending try block”); } catch(ArithmeticException e) { // Catch the exception System.out.println(“Arithmetic exception caught”); } System.out.println(“After try block”); return; } }

  13. The try Block 2 • EXAMPLE – TestLoopTryCatch 01 UsingTryCatch • public class TestLoopTryCatch { public static void main(String[] args) { int i = 12; for(int j=3 ;j>=-1 ; j--) try { System.out.println(“Try block entered “ + “i = “+ i + “ j = “+j); System.out.println(i/j); // Divide by 0 - exception thrown System.out.println(“Ending try block”); } catch(ArithmeticException e) { // Catch the exception System.out.println(“Arithmetic exception caught”); } System.out.println(“After try block”); return; } }

  14. Multiple Catch Blocks • try { // Code that may throw exceptions } catch(ArithmeticException e) { // Code for handling ArithmeticException exceptions } catch(IndexOutOfBoundsException e) { // Code for handling IndexOutOfBoundsException exceptions } // Execution continues here...

  15. Finally Block • try { // Code that may throw exceptions... } catch(ExceptionType1 e) { // Code to handle exceptions of type ExceptionType1 or subclass } catch(ExceptionType2 e) { // Code to handle exceptions of type ExceptionType2 or subclass ... // more catch blocks if necessary } finally { // Code always to be executed after try block code }

  16. Structuring a Method • Execution Sequence • EXAMPLE- TryBlockTest 01 UsingTryCatch • Normal Execution of a Method

  17. Execution Sequence

  18. Unnormal ExecutionExecution When an Exception Is Thrown

  19. Unnormal ExecutionExecution When an Exception Is Not Caught

  20. Nested try Blocks • try { try { //1st inner try block code... } catch( Exception1 ) { //... } //Outer try block code... try { //2nd inner try block code... }catch( Exception1 e ) { //try block code... } }catch( Exception2 e ){ //Outer catch block code... }

  21. Nested try Blocks • try { try { //1st inner try block code... } catch( Exception1 ) { //... } //Outer try block code... try { //2nd inner try block code... }catch( Exception1 e ) { //try block code... } }catch( Exception2 e ){ //Outer catch block code... }

  22. Rethrowing an Exception • try { // Code that originates an arithmetic exception } catch(ArithmeticException e) { // Deal with the exception here throw e; // Rethrow the exception to the calling program }

  23. The Throwable Class The exception object that is passed to a catch block can provide additional information about the nature of the problem that originated it. To understand more about this, let’s first look at the members of the base class for exceptions Throwable because these will be inherited by all exception classes and are therefore contained in every exception object that is thrown.

  24. The Throwable Class • A message, which I have just referred to as being initialized by a constructor • A record of the execution stack at the time the object was created • getMessage() • printStackTrace() • printStackTrace(PrintStream s) e.fillInStackTrace(); // Record the throw point throw e; // Rethrow the exception

  25. EXAMPLE - Dishing the Dirt on • public static int divide(int[] array, int index) { try { System.out.println(“\nFirst try block in divide() entered”); array[index + 2] = array[index]/array[index + 1]; System.out.println(“Code at end of first try block in divide()”); return array[index + 2]; } catch(ArithmeticException e) { System.err.println(“Arithmetic exception caught in divide()\n” + “\nMessage in exception object:\n\t” + e.getMessage()); System.err.println(“\nStack trace output:\n”); e.printStackTrace(); System.err.println(“\nEnd of stack trace output\n”); } catch(ArrayIndexOutOfBoundsException e) { System.err.println(“Index-out-of-bounds exception caught in divide()\n” + “\nMessage in exception object:\n\t” + e.getMessage()); System.err.println(“\nStack trace output:\n”); e.printStackTrace(); System.out.println(“\nEnd of stack trace output\n”); } finally { System.err.println(“finally clause in divide()”); } System.out.println(“Executing code after try block in divide()”); return array[index + 2]; }

  26. Standard Exceptions • The majority of predefined exception classes in Java don’t add further information about the conditions that created the exception. The type alone serves to differentiate one exception from another in most cases. • This general lack of additional information is because it can be gleaned in the majority of cases only by prior knowledge of the computation that is being carried out when the exception occurs, and the only person who is privy to that is you, since you’re writing the program.

  27. Defining Your Own Exceptions public class DreadfulProblemException extends Exception { // Constructors public DreadfulProblemException(){ } // Default constructor public DreadfulProblemException(String s) { super(s); // Call the base class constructor } }

  28. EXAMPLE:Defining Your Own Exception Class 02 Exception Objects • public class ZeroDivideException extends Exception { private int index = -1; // Index of array element causing error // Default Constructor public ZeroDivideException(){ } // Standard constructor public ZeroDivideException(String s) { super(s); // Call the base constructor } public ZeroDivideException(int index) { super(“/ by zero”); // Call the base constructor this.index = index; // Set the index value } // Get the array index value for the error public int getIndex() { return index; // Return the index value } // Standard constructor public ZeroDivideException(String s) { super(s); // Call the base constructor } public ZeroDivideException(int index) { super(“/ by zero”); // Call the base constructor this.index = index; // Set the index value } // Get the array index value for the error public int getIndex() { return index; // Return the index value } }

  29. EXAMPLE:Using Your Own Exception Class • public static int divide(int[] array, int index) throws ZeroDivideException { try { System.out.println(“First try block in divide() entered”); array[index + 2] = array[index]/array[index + 1]; System.out.println(“Code at end of first try block in divide()”); return array[index + 2]; } catch(ArithmeticException e) { System.out.println(“Arithmetic exception caught in divide()”); throw new ZeroDivideException(index + 1); // Throw new exception } catch(ArrayIndexOutOfBoundsException e) { System.out.println( “Index-out-of-bounds index exception caught in divide()”); } System.out.println(“Executing code after try block in divide()”); return array[index + 2]; }

  30. EXAMPLE:Using Your Own Exception Class • public static void main(String[ ] args) { int[ ] x = {10, 5, 0}; // Array of three integers // This block only throws an exception if method divide() does try { System.out.println(“First try block in main()entered”); System.out.println(“result = “ + divide(x,0)); // No error x[1] = 0; // Will cause a divide by zero System.out.println(“result = “ + divide(x,0)); // Arithmetic error x[1] = 1; // Reset to prevent divide by zero System.out.println(“result = “ + divide(x,1)); // Index error } catch(ZeroDivideException e) { int index = e.getIndex(); // Get the index for the error if(index > 0) { // Verify it is valid and now fix the array x[index] = 1; // ...set the divisor to 1... x[index + 1] = x[index - 1]; // ...and set the result System.out.println(“Zero divisor corrected to “ + x[index]); } } catch(ArithmeticException e) { System.out.println(“Arithmetic exception caught in main()”); } catch(ArrayIndexOutOfBoundsException e) { System.out.println(“Index-out-of-bounds exception caught in main()”); } System.out.println(“Outside first try block in main()”); }

More Related