SlideShare ist ein Scribd-Unternehmen logo
1 von 31
Exceptions
Class Exception


java.lang.Object java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
java.lang.IllegalArgumentException
Throwing an Exception
public class SSN {
   private String SSNumber;

   public SSN (String s) {
      if (isValidSSN(s) )
         SSNumber = s;
      else
         throw new IllegalSSNException("Invalid SSN: "+s);
   }
...
Defining a new Exception
public class SSN {
   private String SSNumber;

   public SSN (String s) {
      if (isValidSSN(s) )
         SSNumber = s;
      else
         throw new IllegalSSNException("Invalid SSN: "+s);
   }
...



      This exception is not in the Java class library.
Extend an Existing Exception
public class IllegalSSNException
          extends IllegalArgumentException {
     public IllegalSSNException(String message) {
         super (message);
     }
}
Exception Hierarchy
                   Java.lang.Object

                      Throwable


        Error                          Exception



                IOException              RuntimeException


                              IllegalArgumentException

                                IndexOutOfBoundsException

IllegalSSNException                  NullPointerException
What Happens When an
      Exception is Thrown?
• The Runtime System looks for a method
  that can handle the exception
• If no such method is found, the Runtime
  System handles the exception and
  terminates the program
• The Runtime System looks at the most
  recently called method, and backs up all the
  way to the main program
Main          A:                B:      C:
 A();           B();             C();



Main program starts




                       Main
                       Runtime Stack
Main          A:                B:      C:
 A();           B();             C();



Main program calls A




                       A
                       Main
                       Runtime Stack
Main        A:               B:      C:
 A();        B();             C();



A calls B




                    B
                    A
                    Main
                    Runtime Stack
Main        A:               B:      C:
 A();        B();             C();



B calls C




                    C
                    B
                    A
                    Main
                    Runtime Stack
Main          A:                B:      C:
 A();           B();             C();   exception!



C causes an exception




                       C
                       B
                       A
                       Main
                       Runtime Stack
Main           A:                B:         C:
 A();            B();             C();      exception!



C cannot handle the exception
The JVM terminates C, removes it from the        JVM
stack, and throws the exception to B


                        C
                        B
                        A
                        Main
                        Runtime Stack
Main           A:                B:                 C:
 A();            B();              C();
                                 exception!

                                              JVM
B cannot handle the exception
The JVM terminates B, removes it from the
stack, and throws the exception to A




                        A
                        Main
                        Runtime Stack
Main           A:              B:           C:
 A();            B();           C();
               exception!

                           JVM
A cannot handle the exception
The JVM terminates A, removes it from the
stack, and throws the exception to Main




                     Main
                     Runtime Stack
Main            A:               B:             C:
  A();            B();             C();
 exception!

            JVM
Main cannot handle the exception
The JVM terminates Main, removes it from the
stack, and prints a stack trace to the console




                         Runtime Stack
Main          A:              B:               C:
 A();           B();            C();
                                                exception!




  A, B and C are all exception propagators because by
  not handling the exception, they pass it back to the
  calling program.

  If one of these methods knew how to handle the
  exception, it would be an exception catcher
The try/catch block
try {


    some statements here which may throw an exception

catch (Exception e) {

    some statements to be executed if an Exception happens

}

    the program then continues...
Example
while (true) {
  try {
    num = JOptionPane.showInputDialog
                         null, "Enter a number");
    n = Integer.parseInt(num);
    JOptionPane.showMessageDialog
                        (null,"Thank you for entering "+n);
     if(n==0)System.exit(0);
  }
  catch (Exception e) {
     JOptionPane.showMessageDialog
                   (null,"That is not a number! Try again");
  }
}
while (true) {
  try {
    num = JOptionPane.showInputDialog
                         null, "Enter a number");
    n = Integer.parseInt(num);
    JOptionPane.showMessageDialog
                        (null,"Thank you for entering "+n);
     if(n==0)System.exit(0);
  }
  catch (Exception e) {
     JOptionPane.showMessageDialog
                   (null,"That is not a number! Try again");
  }
}



This is very general... any exception that happens
will be caught here.
What kind of exception does parseInt throw?
parseInt
      public static int parseInt(String s) throws NumberFormatException

while (true) {
  try {
    num = JOptionPane.showInputDialog
                         null, "Enter a number");
    n = Integer.parseInt(num);
    JOptionPane.showMessageDialog
                        (null,"Thank you for entering "+n);
     if(n==0)System.exit(0);
  }
  catch (NumberFormatException e) {
     JOptionPane.showMessageDialog
                   (null,"That is not a number! Try again");
  }
}
What if multiple exceptions can be thrown in the try block?
try {
   n = Integer.parseInt(num);
   a[i] = n;
}
  catch (NumberFormatException nfe) {
      JOptionPane.showMessageDialog(null,"Not a number!");
  }
  catch (IndexOutOfBoundsException ioob) {
      System.out.println("Bad array index: "+i);
  }
  catch (Exception e) {
      System.out.println("An exception occurred.");
  }

        The JVM will go through the catch blocks top
        to bottom until a matching exception is found
What if multiple exceptions can be thrown in the try block?
try {
   n = Integer.parseInt(num);
   a[i] = n;
}
  catch (Exception e) {
      System.out.println("An exception occurred.");
  }
  catch (NumberFormatException nfe) {
      JOptionPane.showMessageDialog(null,"Not a number!");
  }
  catch (IndexOutOfBoundsException ioob) {
      System.out.println("Bad array index: "+i);
  }

 This is why the order of the exceptions listed is important..
 because of the class hierarchy and inheritance, a
 NumberFormatException is an Exception, and the first catch
 block will handle it.
Try/Catch Flow
Example from the SSN class
ssnRead = inFile.readLine();
while (ssnRead != null) {
  try {
    mySSN = new SSN(ssnRead);
    mySubscripts.append(Integer.toString(subscript++)+"n");
    myTextArea.append(mySSN+"n");
    ssnRead = inFile.readLine();
  }
  catch (IllegalSSNException issne) {
      System.out.println(issne.getMessage());
  }
}

                    There is an error here!
 If an exception occurs, the next line from the file is not read.
 This needs to be whether or not there is an exception.
The finally block is executed whether or not an exception occurs.

ssnRead = inFile.readLine();
while (ssnRead != null) {
  try {
    mySSN = new SSN(ssnRead);
    mySubscripts.append(Integer.toString(subscript++)+"n");
    myTextArea.append(mySSN+"n");
  }
  catch (IllegalSSNException issne) {
    System.out.println(issne.getMessage());
  }
  finally {
    ssnRead = inFile.readLine();
  }
}
Try/catch/finally flow
Checked and Unchecked Exceptions

• Excluding exceptions in the class
  RuntimeException, the compiler must find a
  catcher or a propagator for every exception.
• RuntimeException is an unchecked
  exception.
• All other exceptions are checked
  exceptions.
class A {
    public A () throws NumberFormatException {}
}


class B {
    public void C () {                     This is OK; the
        A xyz = new A();                   exception will
    }                                      be propagated.
}

class B {
    try {                                   This is OK; the
        A xyz = new A();                    exception will
    }                                       be caught.
    catch {NumberFormatException nfe {
    }
class A {
    public A () throws IOException {}
}

class B {
    public void C () throws IOException
{
                                          This is OK; the
                                          exception will
        A xyz = new A();
                                          be propagated.
    }
}

class B {
    try {                                 This is OK; the
        A xyz = new A();                  exception will
    }                                     be caught.
    catch {IOException nfe {
    }

Weitere ähnliche Inhalte

Was ist angesagt?

Checking Wine with PVS-Studio and Clang Static Analyzer
Checking Wine with PVS-Studio and Clang Static AnalyzerChecking Wine with PVS-Studio and Clang Static Analyzer
Checking Wine with PVS-Studio and Clang Static AnalyzerAndrey Karpov
 
Conditional Control
Conditional ControlConditional Control
Conditional ControlAnar Godjaev
 
Handling Exceptions In C & C++ [Part B] Ver 2
Handling Exceptions In C & C++ [Part B] Ver 2Handling Exceptions In C & C++ [Part B] Ver 2
Handling Exceptions In C & C++ [Part B] Ver 2ppd1961
 
5 c control statements looping
5  c control statements looping5  c control statements looping
5 c control statements loopingMomenMostafa
 
Exception handling
Exception handlingException handling
Exception handlingKapish Joshi
 
PVS-Studio is there to help CERN: analysis of Geant4 project
PVS-Studio is there to help CERN: analysis of Geant4 projectPVS-Studio is there to help CERN: analysis of Geant4 project
PVS-Studio is there to help CERN: analysis of Geant4 projectPVS-Studio
 
PVS-Studio Meets Octave
PVS-Studio Meets Octave PVS-Studio Meets Octave
PVS-Studio Meets Octave PVS-Studio
 
The operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzerThe operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzerAndrey Karpov
 
C++ control structure
C++ control structureC++ control structure
C++ control structurebluejayjunior
 
Looping Statement And Flow Chart
 Looping Statement And Flow Chart Looping Statement And Flow Chart
Looping Statement And Flow ChartRahul Sahu
 
CppCat Checks OpenMW: Not All is Fine in the Morrowind Universe
CppCat Checks OpenMW: Not All is Fine in the Morrowind UniverseCppCat Checks OpenMW: Not All is Fine in the Morrowind Universe
CppCat Checks OpenMW: Not All is Fine in the Morrowind UniverseAndrey Karpov
 
What is to loop in c++
What is to loop in c++What is to loop in c++
What is to loop in c++03446940736
 
Loops in matlab
Loops in matlabLoops in matlab
Loops in matlabTUOS-Sam
 

Was ist angesagt? (20)

Checking Wine with PVS-Studio and Clang Static Analyzer
Checking Wine with PVS-Studio and Clang Static AnalyzerChecking Wine with PVS-Studio and Clang Static Analyzer
Checking Wine with PVS-Studio and Clang Static Analyzer
 
Java Programmin: Selections
Java Programmin: SelectionsJava Programmin: Selections
Java Programmin: Selections
 
Conditional Control
Conditional ControlConditional Control
Conditional Control
 
Standard exceptions
Standard exceptionsStandard exceptions
Standard exceptions
 
Handling Exceptions In C & C++ [Part B] Ver 2
Handling Exceptions In C & C++ [Part B] Ver 2Handling Exceptions In C & C++ [Part B] Ver 2
Handling Exceptions In C & C++ [Part B] Ver 2
 
Loops in c
Loops in cLoops in c
Loops in c
 
5 c control statements looping
5  c control statements looping5  c control statements looping
5 c control statements looping
 
Exception handling
Exception handlingException handling
Exception handling
 
PVS-Studio is there to help CERN: analysis of Geant4 project
PVS-Studio is there to help CERN: analysis of Geant4 projectPVS-Studio is there to help CERN: analysis of Geant4 project
PVS-Studio is there to help CERN: analysis of Geant4 project
 
Java Programming: Loops
Java Programming: LoopsJava Programming: Loops
Java Programming: Loops
 
PVS-Studio Meets Octave
PVS-Studio Meets Octave PVS-Studio Meets Octave
PVS-Studio Meets Octave
 
The operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzerThe operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzer
 
C++ control structure
C++ control structureC++ control structure
C++ control structure
 
CodeChecker summary 21062021
CodeChecker summary 21062021CodeChecker summary 21062021
CodeChecker summary 21062021
 
Looping Statement And Flow Chart
 Looping Statement And Flow Chart Looping Statement And Flow Chart
Looping Statement And Flow Chart
 
Comp ppt (1)
Comp ppt (1)Comp ppt (1)
Comp ppt (1)
 
CppCat Checks OpenMW: Not All is Fine in the Morrowind Universe
CppCat Checks OpenMW: Not All is Fine in the Morrowind UniverseCppCat Checks OpenMW: Not All is Fine in the Morrowind Universe
CppCat Checks OpenMW: Not All is Fine in the Morrowind Universe
 
What is to loop in c++
What is to loop in c++What is to loop in c++
What is to loop in c++
 
C++ boot camp part 1/2
C++ boot camp part 1/2C++ boot camp part 1/2
C++ boot camp part 1/2
 
Loops in matlab
Loops in matlabLoops in matlab
Loops in matlab
 

Ähnlich wie Exceptions

OCJP Samples Questions: Exceptions and assertions
OCJP Samples Questions: Exceptions and assertionsOCJP Samples Questions: Exceptions and assertions
OCJP Samples Questions: Exceptions and assertionsHari kiran G
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentrohitgudasi18
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception HandlingPrabhdeep Singh
 
Exceptions irst
Exceptions irstExceptions irst
Exceptions irstjkumaranc
 
Multiple Choice Questions for Java interfaces and exception handling
Multiple Choice Questions for Java interfaces and exception handlingMultiple Choice Questions for Java interfaces and exception handling
Multiple Choice Questions for Java interfaces and exception handlingAbishek Purushothaman
 
Exception Handling
Exception HandlingException Handling
Exception HandlingReddhi Basu
 
Exception Handling
Exception HandlingException Handling
Exception HandlingSunil OS
 
exceptionhandlinginjava-140224181412-phpapp02.pptx
exceptionhandlinginjava-140224181412-phpapp02.pptxexceptionhandlinginjava-140224181412-phpapp02.pptx
exceptionhandlinginjava-140224181412-phpapp02.pptxARUNPRANESHS
 
Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliabilitymcollison
 

Ähnlich wie Exceptions (20)

OCJP Samples Questions: Exceptions and assertions
OCJP Samples Questions: Exceptions and assertionsOCJP Samples Questions: Exceptions and assertions
OCJP Samples Questions: Exceptions and assertions
 
Csharp_Chap04
Csharp_Chap04Csharp_Chap04
Csharp_Chap04
 
Exceptions
ExceptionsExceptions
Exceptions
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application development
 
Java concurrency questions and answers
Java concurrency questions and answers Java concurrency questions and answers
Java concurrency questions and answers
 
Nalinee java
Nalinee javaNalinee java
Nalinee java
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception Handling
 
Exceptions irst
Exceptions irstExceptions irst
Exceptions irst
 
Multiple Choice Questions for Java interfaces and exception handling
Multiple Choice Questions for Java interfaces and exception handlingMultiple Choice Questions for Java interfaces and exception handling
Multiple Choice Questions for Java interfaces and exception handling
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 
Java programs
Java programsJava programs
Java programs
 
7
77
7
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
exceptionhandlinginjava-140224181412-phpapp02.pptx
exceptionhandlinginjava-140224181412-phpapp02.pptxexceptionhandlinginjava-140224181412-phpapp02.pptx
exceptionhandlinginjava-140224181412-phpapp02.pptx
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
E5
E5E5
E5
 
Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliability
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 

Exceptions

  • 3. Throwing an Exception public class SSN { private String SSNumber; public SSN (String s) { if (isValidSSN(s) ) SSNumber = s; else throw new IllegalSSNException("Invalid SSN: "+s); } ...
  • 4.
  • 5. Defining a new Exception public class SSN { private String SSNumber; public SSN (String s) { if (isValidSSN(s) ) SSNumber = s; else throw new IllegalSSNException("Invalid SSN: "+s); } ... This exception is not in the Java class library.
  • 6. Extend an Existing Exception public class IllegalSSNException extends IllegalArgumentException { public IllegalSSNException(String message) { super (message); } }
  • 7. Exception Hierarchy Java.lang.Object Throwable Error Exception IOException RuntimeException IllegalArgumentException IndexOutOfBoundsException IllegalSSNException NullPointerException
  • 8. What Happens When an Exception is Thrown? • The Runtime System looks for a method that can handle the exception • If no such method is found, the Runtime System handles the exception and terminates the program • The Runtime System looks at the most recently called method, and backs up all the way to the main program
  • 9. Main A: B: C: A(); B(); C(); Main program starts Main Runtime Stack
  • 10. Main A: B: C: A(); B(); C(); Main program calls A A Main Runtime Stack
  • 11. Main A: B: C: A(); B(); C(); A calls B B A Main Runtime Stack
  • 12. Main A: B: C: A(); B(); C(); B calls C C B A Main Runtime Stack
  • 13. Main A: B: C: A(); B(); C(); exception! C causes an exception C B A Main Runtime Stack
  • 14. Main A: B: C: A(); B(); C(); exception! C cannot handle the exception The JVM terminates C, removes it from the JVM stack, and throws the exception to B C B A Main Runtime Stack
  • 15. Main A: B: C: A(); B(); C(); exception! JVM B cannot handle the exception The JVM terminates B, removes it from the stack, and throws the exception to A A Main Runtime Stack
  • 16. Main A: B: C: A(); B(); C(); exception! JVM A cannot handle the exception The JVM terminates A, removes it from the stack, and throws the exception to Main Main Runtime Stack
  • 17. Main A: B: C: A(); B(); C(); exception! JVM Main cannot handle the exception The JVM terminates Main, removes it from the stack, and prints a stack trace to the console Runtime Stack
  • 18. Main A: B: C: A(); B(); C(); exception! A, B and C are all exception propagators because by not handling the exception, they pass it back to the calling program. If one of these methods knew how to handle the exception, it would be an exception catcher
  • 19. The try/catch block try { some statements here which may throw an exception catch (Exception e) { some statements to be executed if an Exception happens } the program then continues...
  • 20. Example while (true) { try { num = JOptionPane.showInputDialog null, "Enter a number"); n = Integer.parseInt(num); JOptionPane.showMessageDialog (null,"Thank you for entering "+n); if(n==0)System.exit(0); } catch (Exception e) { JOptionPane.showMessageDialog (null,"That is not a number! Try again"); } }
  • 21. while (true) { try { num = JOptionPane.showInputDialog null, "Enter a number"); n = Integer.parseInt(num); JOptionPane.showMessageDialog (null,"Thank you for entering "+n); if(n==0)System.exit(0); } catch (Exception e) { JOptionPane.showMessageDialog (null,"That is not a number! Try again"); } } This is very general... any exception that happens will be caught here. What kind of exception does parseInt throw?
  • 22. parseInt public static int parseInt(String s) throws NumberFormatException while (true) { try { num = JOptionPane.showInputDialog null, "Enter a number"); n = Integer.parseInt(num); JOptionPane.showMessageDialog (null,"Thank you for entering "+n); if(n==0)System.exit(0); } catch (NumberFormatException e) { JOptionPane.showMessageDialog (null,"That is not a number! Try again"); } }
  • 23. What if multiple exceptions can be thrown in the try block? try { n = Integer.parseInt(num); a[i] = n; } catch (NumberFormatException nfe) { JOptionPane.showMessageDialog(null,"Not a number!"); } catch (IndexOutOfBoundsException ioob) { System.out.println("Bad array index: "+i); } catch (Exception e) { System.out.println("An exception occurred."); } The JVM will go through the catch blocks top to bottom until a matching exception is found
  • 24. What if multiple exceptions can be thrown in the try block? try { n = Integer.parseInt(num); a[i] = n; } catch (Exception e) { System.out.println("An exception occurred."); } catch (NumberFormatException nfe) { JOptionPane.showMessageDialog(null,"Not a number!"); } catch (IndexOutOfBoundsException ioob) { System.out.println("Bad array index: "+i); } This is why the order of the exceptions listed is important.. because of the class hierarchy and inheritance, a NumberFormatException is an Exception, and the first catch block will handle it.
  • 26. Example from the SSN class ssnRead = inFile.readLine(); while (ssnRead != null) { try { mySSN = new SSN(ssnRead); mySubscripts.append(Integer.toString(subscript++)+"n"); myTextArea.append(mySSN+"n"); ssnRead = inFile.readLine(); } catch (IllegalSSNException issne) { System.out.println(issne.getMessage()); } } There is an error here! If an exception occurs, the next line from the file is not read. This needs to be whether or not there is an exception.
  • 27. The finally block is executed whether or not an exception occurs. ssnRead = inFile.readLine(); while (ssnRead != null) { try { mySSN = new SSN(ssnRead); mySubscripts.append(Integer.toString(subscript++)+"n"); myTextArea.append(mySSN+"n"); } catch (IllegalSSNException issne) { System.out.println(issne.getMessage()); } finally { ssnRead = inFile.readLine(); } }
  • 29. Checked and Unchecked Exceptions • Excluding exceptions in the class RuntimeException, the compiler must find a catcher or a propagator for every exception. • RuntimeException is an unchecked exception. • All other exceptions are checked exceptions.
  • 30. class A { public A () throws NumberFormatException {} } class B { public void C () { This is OK; the A xyz = new A(); exception will } be propagated. } class B { try { This is OK; the A xyz = new A(); exception will } be caught. catch {NumberFormatException nfe { }
  • 31. class A { public A () throws IOException {} } class B { public void C () throws IOException { This is OK; the exception will A xyz = new A(); be propagated. } } class B { try { This is OK; the A xyz = new A(); exception will } be caught. catch {IOException nfe { }