1 / 20

Java Exceptions

Java Exceptions. Overview . An exception is an unusual circumstance, such as an error condition, that must be handled in a non-standard way. Java and many other languages (including C++), exceptions serve as a standard mechanism for handling execution error conditions.

schuyler
Download Presentation

Java Exceptions

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 Exceptions

  2. Overview • An exception is an unusual circumstance, such as an error condition, that must be handled in a non-standard way. • Java and many other languages (including C++), exceptions serve as a standard mechanism for handling execution error conditions. • Provides for handling unusual cases at the appropriate level(s). • For example, an airplane could have a stuck wing flap detected in a very low-level method monitoring a wing flap's position. • No ability to communicate information directly to the pilot. • A wing flap exception can be reported upward to the higher levels that call the low-level method where the exception is detected. • The higher level layers, with broader status information, could automatically adjust other control surfaces and report the wing flap exception to the pilot.

  3. A Little Demo public class Test { public static void main(String[] args) { System.out.println(5/0); }} javac Test.javajava TestException in thread "main" java.lang.ArithmeticException: / by zero at Test.main(Test.java:3)

  4. Exception Example public class Test { public static void main(String[] args) { try { System.out.println( 5 / 0); } catch (ArithmeticException a) { System.out.println("You're dividing by zero!"); } }} This will catch and handle any ArithmeticException. Other exceptions will still get the language system’s default behavior. javac Test.javajava TestYou're dividing by zero!

  5. Exception Mechanism The exception mechanism consists of three parts: • definition of the exception class • throwing the exception when exceptional condition is detected • catching or handling the exception (try and catch).

  6. Exercise 1A - List line numbers executed and output • System.out.print("1"); • try { • System.out.print("2"); • if (true) throw new Exception(); • System.out.print("3"); • } • catch (Exception e) { • System.out.print("4"); • } • finally { • System.out.print("5"); • } • System.out.println("6");

  7. Exercise 1B - List line numbers executed and output • public class Exercise1 { • static void f1() { • System.out.print("1"); • try { • System.out.print("2"); • f2(); • System.out.print("3"); • } • catch (Exception e) { System.out.print("4"); } • finally { System.out.print("5"); } • System.out.println("6"); • } • static void f2 () throws Exception { • if (true) throw new Exception(); • } • public static void main(String s[]) { f1(); } • }

  8. Exercise 1C - List line numbers executed and output • public class Exercise1 { • static void f1() throws Exception { • System.out.print("1"); • try { • System.out.print("2"); • f2(); • System.out.print("3"); • } • catch (Exception e) { System.out.print("4"); throw e; } • finally { System.out.print("5"); } • System.out.println("6"); • } • static void f2 () throws Exception { • if (true) throw new Exception(); • } • public static void main(String s[]) throws Exception { • f1(); • } • } 1245Exception thread "main" java.lang.Exception at Exercise1.f2(Exercise1.java:15) at Exercise1.f1(Exercise1.java:6) at Exercise1.main(Exercise1.java:19)

  9. Define • Generally, an exception class inherits from the parent class Exception. • The exception class definition minimally defines a class constructor but may also provide methods for analysis of the conditions causing the exception. • The following is a typical class definition for counterExceptionwith a constructor that copies a string message complaintpresumably detailing the cause of the exception. • An example of the constructor's use illustrates a new counterException created with the complaint that count failed.

  10. Define and Use Example Define class counterException extends Exception {   String complaint; public counterException(String complaint){      this.complaint = complaint;   }  public String toString(){  return "counter Exception " + complaint; } } Use new counterException("count failed.");

  11. Throw • When an error condition is detected, it is necessary to handle it immediately where detected or throw the exception to the calling method. • Exception handling is a mechanism for transferring control from where an error occurred to where it can be handled most appropriately. • After the exception is thrown, the throwing method terminates and execution control is immediately passed backward along the chain of callers from where the exception was thrown. • Any method along the calling chain can: • handle the exception and continue with execution, • handle the exception and again throw the exception to the calling method to handle • or do nothing, terminate immediately and let the calling method deal with the exception. • The down method below is an example of throwing an exception, in this case when the counter n becomes negative.

  12. Throw Example public int down() throws counterException {   if (n <= 0) throw new counterException( n + " count Down failed.");   return --n; } • The down method is an example of throwing an exception, in this case when the counter n becomes negative. • If exception is thrown, execution does not reach return --n;

  13. Catch • Handling an exception consists of trying a method that throws an exception and catching a thrown exception. • Catching an exception prevents the exception from being passed to a higher level calling method. • If an exception is not caught, the method terminates immediately and control is passed to the higher level calling method so that it might catch the exception. • Consider the following example which causes a counterException to be thrown by method down when the counter becomes negative. • The try and catch go together to define the method that throws the exception, down, and the exception to be caught, counterException. • Only if an exception is thrown will it be caught and the catch statement(s) executed. • Any statements following the catch would be executed as normal.

  14. Catch Example Catch try {  aCounter.down( ); } catch (counterException ce) { System.out.println("" + ce); } Throw public int down() throws counterException {   if (n <= 0) throw new counterException( n + " count Down failed.");   return --n; }

  15. Throwing exceptions to caller • When an exception is not handled in a method it must be thrown to the higher level calling method. • That method must state that it throws an exception as throws counterException. • The down method listed earlier does not handle or catch the counterException thrown so the exception is thrown back to the calling method, action. • The direct effect of down throwing an exception is to terminate its execution, passing execution to the catch, so that the remaining statements of down (i.e. return --n) are not executed. public int down() throws counterException {   if (n <= 0) throw new counterException( n + " count Down failed.");   return --n; }

  16. Finally • try – Invokes a method that throws an exception. • catch – Point of execution of exception throw. • finally - Always executed at end of a try block.

  17. class counterException extends Exception {  // Define •   String complaint; •   public counterException(String c)  { •     this.complaint = c;  •   } •   public String toString( ) { •     return "counter Exception “ + complaint;  •   } • } • class counter { •   int n = 0; •   public int zero() { return n=0; } •   public int up() { return ++n; } •   public int down() throws counterException { // Throw • if (n <= 0) • throw new counterException •          (n + " count Down failed."); •     return --n; •   } • } Exception Class Example

  18. public class Example { • public static void main( String args[] ) { • counter aCounter = new counter( ); • aCounter.zero( ); • aCounter.up(); • try {  aCounter.down( ); } • catch(counterException ce) {  // Catch •         System.out.println("" + ce);  •   } • try {  aCounter.down( ); } • catch(counterException ce) {  // Catch •         System.out.println("" + ce);  •   } • finally { • System.out.println(“Finally”); •   } • } • } Exception Class Use Example

  19. Exercise 2 • class counterException extends Exception { •   String complaint; •   public counterException(String c){ this.complaint = c; } •   public String toString( ) { return "counter Exception “ + complaint; } • } • class counter { •   int n = 0; •   public int zero() { return n=0; } •   public int up() { return ++n; } •   public int down() throws counterException { • if (n <= 0) throw new counterException (n + " count Down failed."); •     return --n; •   } • } • public class Example { • public static void main( String args[] ) { • counter aCounter = new counter( ); • aCounter.zero( ); • aCounter.up(); • try {  aCounter.down( ); } • catch(counterException ce) { System.out.println("" + ce); } • try {  aCounter.down( ); } • catch(counterException ce) { System.out.println("" + ce); } • finally { System.out.println(“Finally”); } • } • } • List the sequence of line numbers executed and output. • The catch is defined in main method but is executed by the throw. Is the catch visible to the throw? • What does the throw and catch resemble?

  20. Exercise 2 Continued • class counterException extends Exception { •   String complaint; •   public counterException(String c){ this.complaint = c; } •   public String toString( ) { return "counter Exception “ + complaint; } • } • class counter { •   int n = 0; •   public int zero() { return n=0; } •   public int up() { return ++n; } •   public int down() throws counterException { • if (n <= 0) throw new counterException (n + " count Down failed."); •     return --n; •   } • } • public class Example { • public static void main( String args[] ) throws Exception{ • counter aCounter = new counter( ); • aCounter.zero( ); • aCounter.up(); • aCounter.down( );  • aCounter.down( ); • System.out.println(“Completed”);  • } • } • List the sequence of line numbers executed and output. • What occurs at Line 21?

More Related