SlideShare a Scribd company logo
1 of 63
Exception Handling
Throwing Exceptions
   What is a good program? A program that is
    reliable?

   Not just giving correct answer on correct input

   Should protect against possible errors (invalid
    password, not a picture file, etc)
Good programs
   Need a robust program, reliable in the eyes of a
    novice user

   It should not (“cannot”) crash easily - what if
    Word always crashed when you hit the control
    key?
Good Programs
   How do we ensure a robust program?
   Option 1 – return a special value to determine if
    the method succeeded or failed
       Ex. Make withdraw return true or false
   What’s wrong with this?
     Calling method may not check answer
     Calling method may not know what to do
Good Programs
   Option 2 - Use exceptions
   Exception – an error condition that can occur
    during the normal course of a program
    execution
   Exception handling is another form of control
    structure (like ifs and switch statements)
       When an error is encountered, the normal flow of
        the program is stopped and the exception is handled
Exceptions
   We say an exception is thrown when it occurs

   When the exception-handling code is executed,
    the error is caught

   Examples:
     Dividing by zero
     Accessing a null object
Exceptions
   What happens when exceptions occur?
       An Exception object is thrown

   What happens when an Exception is thrown?
       normal execution stops and exception handling begins

   What does the Exception object know?
       the name of the problem
       the location where it occurred
       and more…
Exceptions
   Why use exceptions?
   consistency (everyone else does it)
       Java API classes use exceptions.
       Other programming languages do too!

   flexibility
       programmer can decide how to fix problems.

   simplicity
       Easy to pinpoint problems.
Handling Exceptions
   Do nothing
        program crashes if the exception occurs!

   Propagate (throw) it
        tell the method’s caller about it and let them decide what
         to do


   Resolve (try-catch) it in our method
        fix it or tell the user about it and let them decide what to
         do
Handling Exceptions
   So far, we have let the system handle exceptions
int score = in.nextInt();


If the user enters “abc123”
Exception in thread "main"
  java.util.InputMismatchException
        at java.util.Scanner.throwFor(Scanner.java:819)
        at java.util.Scanner.next(Scanner.java:1431)
        at java.util.Scanner.nextInt(Scanner.java:2040)
        at java.util.Scanner.nextInt(Scanner.java:2000)
        at Test.main(Test.java:5)
Handling Exceptions
   Says in English:
       System has caught an error described as a
      InputMismatchException
     Thrown because a String cannot be converted to an
        integer

   When system handles, we often get a program crash
   Instead of the system, we can handle to improve
    robustness
Handling Exceptions
   Better solution: Instead of letting the program
    crash, use Exception Handling to improve
    program’s robustness
     Exceptions cannot be ignored
     Exceptions are handled by Exception Handlers
      directly
Throwing Exceptions
    If there is an error in the value of a parameter,
     we can throw exceptions to make the user
     accountable

1.   Decide what type of exception to throw
2.   Test for condition, and throw the exception if
     condition is violated
Example
   Throw an exception object to signal an
    exceptional condition

   Example: What do we do if the amount to
    withdraw is greater than the balance?
       IllegalArgumentException: illegal parameter value
Problem
public class BankAccount
{
  public void withdraw(double amount)
  {
      if (amount > balance)
      {
        ?????????
      }
      balance = balance - amount;
  }
. . .
}
Solution #1
public class BankAccount
{
  public void withdraw(double amount)
  {
      if (amount > balance)
      {
        IllegalArgumentException exception
           = new IllegalArgumentException("Amount
                 exceeds balance");
        throw exception;
      }
      balance = balance - amount;
  }
. . .
}
Solution #2
public class BankAccount
{
  public void withdraw(double amount)
  {
      if (amount > balance)
      {
        throw new IllegalArgumentException("Amount
                 exceeds balance");
      }
      balance = balance - amount;
  }
. . .
}
Throwing Exceptions: Syntax
throw exceptionObject;
Checked/Unchecked Exceptions
   Checked Exception – checked at compile time
     Complier ensures that you are handling a possible
      problem
     These errors are due to external circumstances that
      the programmer cannot prevent
     Majority occur when dealing with input and output
     For example, IOException
Checked/Unchecked Exceptions
   Unchecked Exception = Runtime Exceptions
     Extend the class RuntimeException or Error
     They are the programmer's fault
     Examples of runtime exceptions:
          NumberFormatException
          IllegalArgumentException
          NullPointerException

       Optional to deal with these
   Example of error: OutOfMemoryError
       Can’t do anything about these catastrophic
        problems, so don’t deal with it
Checked/Unchecked Exceptions
   Unchecked Exceptions result from deficiencies
    in your code, so should check on own
     Null object reference
     Sending a negative value to Math.sqrt()



   Checked Exceptions are not the fault of the
    coder
       Problems with the file format, user input, etc.
Checked/Unchecked Exceptions
   Categories aren't perfect:
       Scanner.nextInt throws unchecked
        InputMismatchException
     Programmer cannot prevent users from entering
      incorrect input
     This choice makes the class easy to use for beginning
      programmers
Checked/Unchecked Exceptions
   Deal with checked exceptions principally when
    programming with files and streams
   For example, use a Scanner to read a file
String filename = . . .;
FileReader reader = new FileReader(filename);
Scanner in = new Scanner(reader);
   But, FileReader constructor can throw a
    FileNotFoundException
Handling Checked Exceptions
1.   Handle the exception
2.   Tell compiler that you want method to be
     terminated when the exception occurs
         Use throws specifier so method can throw a
          checked exception
public void read(String filename) throws
    FileNotFoundException
{
    FileReader reader = new
    FileReader(filename);
    Scanner in = new Scanner(reader);
    . . .
}
Handling Checked Exceptions
   throws tells the compiler to “pass the buck” to the
    method that called this method

   Can propagate multiple exceptions:
public void read(String filename) throws IOException,
  ClassNotFoundException


   Can also group using hierarchy
       If method can throw an IOException and
        FileNotFoundException, only use IOException
Handling Checked Exceptions
   Why propagate when we could handle the error
    ourselves?
     We may not know how to
     Let user of my code decide



   Better to declare exception than to handle it
    incompetently
Catching Exceptions
   At some point, an exception should be dealt
    with
       If not, program terminates with error message


   Professional code requires more sophistication –
    cannot just allow errors to kill program
       What would happen if all of my.wisc.edu turned off
        if you entered wrong password?
Catching Exceptions
   To deal with this problem, install exception
    handlers in your code to deal with possible
    exceptions

   Handlers are try/catch statements
Try-Catch
   Put statement(s) that could cause an error in the
    try block

   Error handling code goes in catch block
       Only is executed if there was an error


   Can have multiple catch blocks, one for each
    possible type of exception
try-catch Syntax
try
{
   <try block>
}
catch ( <ExceptionClass> <name> )
{
   <catch block>
}
catch ( <ExceptionClass> <name> )
{
   <catch block>
}…
try
{
  String filename = . . .;
  FileReader reader = new FileReader(filename);
  Scanner in = new Scanner(reader);
  String input = in.next();
  int value = Integer.parseInt(input);
  . . .
}
catch (IOException exception)
{
  exception.printStackTrace();
}
catch (NumberFormatException exception)
{
  System.out.println("Input was not a number");
}
Example
   3 types of error can be thrown
       FileNotFoundException is thrown by
        FileReader constructor  caught by
        IOException clause
       NoSuchElementException is thrown by
        Scanner.next  not caught, thrown to caller
       NumberFormatException is thrown by
        Integer.parseInt()  caught by second clause
Catching Exceptions
   If there are no errors, the catch block is skipped

   If an exception is thrown, the try block stops
    executing immediately and jumps to the catch
    block
Catching Exceptions
Exception Information
   Why do we have Exception objects?
       We can get information on where the error happened
        and what exactly happened


   Exception objects have 2 methods defined:
     getMessage() (what happened?)
     printStackTrace() (where did it happen?)
getMessage
   Returns the data that cause the error
       Example:
    …
    }catch(NumberFormatException e){
      System.out.println(e.getMessage());
    }
printStackTrace
   Prints out a trace of methods that caused the
    error starting at the root of the error
     Where did the exception occur? What method called
      this code to execute..etc.
     This is what the system does when an exception is
      thrown
     Example:

    …
    }catch(NumberFormatException e){
      e.printStackTrace();
    }
Catching ALL Exceptions
public double average( String data )
{
  try
  {
     int sum = 0;
     for ( int i=0; i < data.length(); i++ )
        sum += Integer.parseInt(data.charAt(i));
     return sum/data.length();

    }
     catch ( Exception e ) // catch ALL exceptions
     {
        System.out.println( e );
        return 0;
     }

}
Catching ALL Exceptions
   Why is this probably a bad idea?

   Probably want to handle each type of exception
    differently

   Don't want to catch things like
    NullPointerExeption
Catching Exceptions
   IMPORTANT! Order of catch blocks matters
    } catch (Exception e){
        System.out.println(e.getMessage());
    } catch (NumberFormatException e){
        System.out.println("'" + str + "'not          valid
                    input, Please use digits          only");
    }


   You should go specific to generic
       NumberFormatException is a specific type of the class
        Exception (inheritance)
Demo
p.s.v. main( String [] args )
{
   try {
      String filename = args[0], input;
      scanner = new Scanner( new File(filename) );
      input = scanner.nextLine();
      int value = Integer.parseInt( input );
      double reciprocal = 1.0 / value;
      System.out.println( "rec=" + rec );

    }
    catch ( Exception e )
    {
       S.o.pln( "Found Exception: " + e );
    }
    S.o.pln( "Done" );
}
String filename=args[0], input;
try {
  scanner = new Scanner(new File(filename));
  input = scanner.nextLine();
  int value = Integer.parseInt( input );
  double reciprocal = 1.0 / value;
  System.out.println( "rec=" + rec );
}
catch ( NumberFormatException e ) {
  S.o.pln( input + " is not an integer");
}
catch ( ArithmeticException e ) {
   S.o.pln( "Can't divide by zero" );
}
catch ( FileNotFoundException e ) {
   S.o.pln( filename + " Not Found" );
}
finally { S.o.pln( "Done" ); }
Catching Exceptions
   What if an exception is thrown and there is no
    catch block to match?
       The system handles it (terminates program and
        prints the stack trace)
The finally clause
   Recall that whenever an exception occurs, we
    immediately go to the catch block

   What if there is some code we want to execute
    regardless of whether there was an exception?
       finally block is used
The finally clause
try{
    distance = Double.parseDouble(str);
    if (distance < 0){
      throw new Exception("Negative distance is not
          valid");
    }
    return distance;
} catch (NumberFormatException e){
    System.out.println("'" + str + "'not valid
          input, Please use digits only");
} catch (Exception e){
    System.out.println(e.getMessage());
} finally {
    System.out.println(“Done”);
}
The finally clause
   finally is executed NO MATTER WHAT

   Even if there is a break or return in the try block

   Good for “cleanup” of a method
Throwable    Exception Inheritance Hierarchy
  Exception
     RuntimeException
        NullPointerException
        ArithmeticException
        NegativeArrayIndexException
        IndexOutOfBoundsException
           ArrayIndexOutOfBoundsException
          StringIndexOutOfBoundsException
       IllegalArgumentException
          NumberFormatException
    IOException
       FileNotFoundException
       EOFException
try-catch Control Flow
code before try


   try block

no exceptions occur




 code after try
try-catch Control Flow
code before try

                  exception occurs
   try block                         catch block




code after try
try-catch Control Flow
code before try

                  exception occurs
   try block                         catch block

no exceptions occur




 code after try
try-catch Control Flow
      code before try


          try block
no exceptions
     occurred



  finally block (if it exists)


       code after try
try-catch Control Flow
    code before try

                           exception occurs
        try block                             catch block




finally block (if it exists)


     code after try
try-catch Control Flow
                                        exception occurs
        code before try

                                             true   matches first
            try block                               catch block?
no exceptions
     occurred              1st catch block                 false


                                             true   matches next
                         2nd catch block            catch block?

                                                           false

    finally block (if it exists)

          code after try
Propagating Exceptions
   When a method may throw an exception, either
    directly or indirectly, we call the method an
    exception thrower.

   Every exception thrower must be one of two
    types:
       a catcher, or
       a propagator.
Propagating Exceptions
   An exception catcher is an exception thrower that
    includes a matching catch block for the thrown
    exception.

   An exception propagator does not contain a
    matching catch block.

   A method may be a catcher of one exception
    and a propagator of another.
Example
   The following figure shows a sequence of method calls
    among the exception throwers.
   Method D throws an instance of Exception. The green
    arrows indicate the direction of calls. The red arrows
    show the reversing of call sequence, looking for a
    matching catcher. Method B is the catcher.
   The call sequence is traced by using a stack.
Example
Propagating Exceptions
   If a method is an exception propagator, we need to
    modify its header to declare the type of exceptions the
    method propagates.

   We use the reserved word throws for this declaration.
    public void C( ) throws Exception {
       ...
    }
    public void D( ) throws Exception {
       ...
    }
Propagating Exceptions
   Without the required throws Exception clause,
    the program will not compile.

   However, for exceptions of the type called
    runtime exceptions, the throws clause is optional.
Propagating vs. Catching
   Do not catch an exception that is thrown as a
    result of violating a condition set by the client
    programmer.

   Instead, propagate the exception back to the
    client programmer’s code and let him or her
    handle it.
Exceptions in a Constructor
   We can thrown an exception in the constructor
    if a condition is violated
       For example, we may throw an
        IllegalArgumentException if a parameter value
        is invalid

More Related Content

What's hot

Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Javaankitgarg_er
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaPratik Soares
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handlingDeepak Sharma
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaAdil Mehmoood
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handlingraksharao
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception HandlingLemi Orhan Ergin
 
exception handling in java
exception handling in java exception handling in java
exception handling in java aptechsravan
 
130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handlingHemant Chetwani
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling ConceptsVicter Paul
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapooja kumari
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapriyankazope
 

What's hot (20)

Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handling
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
javaexceptions
javaexceptionsjavaexceptions
javaexceptions
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception Handling
 
exception handling in java
exception handling in java exception handling in java
exception handling in java
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
12 exception handling
12 exception handling12 exception handling
12 exception handling
 
130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handling
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling Concepts
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 

Viewers also liked

String handling session 5
String handling session 5String handling session 5
String handling session 5Raja Sekhar
 
java Basic Programming Needs
java Basic Programming Needsjava Basic Programming Needs
java Basic Programming NeedsRaja Sekhar
 
Class object method constructors in java
Class object method constructors in javaClass object method constructors in java
Class object method constructors in javaRaja Sekhar
 
Java cơ bản java co ban
Java cơ bản java co ban Java cơ bản java co ban
Java cơ bản java co ban ifis
 
kg0000931 Chapter 1 introduction to computers, programs part ia
kg0000931 Chapter 1 introduction to computers, programs part ia kg0000931 Chapter 1 introduction to computers, programs part ia
kg0000931 Chapter 1 introduction to computers, programs part ia kg0000931
 
bai giang java co ban - java cơ bản - bai 1
bai giang java co ban - java cơ bản - bai 1bai giang java co ban - java cơ bản - bai 1
bai giang java co ban - java cơ bản - bai 1ifis
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34myrajendra
 
9781285852744 ppt ch02
9781285852744 ppt ch029781285852744 ppt ch02
9781285852744 ppt ch02Terry Yoast
 
Exception handling
Exception handlingException handling
Exception handlingIblesoft
 
Access Protection
Access ProtectionAccess Protection
Access Protectionmyrajendra
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in JavaVadym Lotar
 

Viewers also liked (20)

Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Java packages
Java packagesJava packages
Java packages
 
String handling session 5
String handling session 5String handling session 5
String handling session 5
 
java Basic Programming Needs
java Basic Programming Needsjava Basic Programming Needs
java Basic Programming Needs
 
Class object method constructors in java
Class object method constructors in javaClass object method constructors in java
Class object method constructors in java
 
Java cơ bản java co ban
Java cơ bản java co ban Java cơ bản java co ban
Java cơ bản java co ban
 
JavaYDL18
JavaYDL18JavaYDL18
JavaYDL18
 
kg0000931 Chapter 1 introduction to computers, programs part ia
kg0000931 Chapter 1 introduction to computers, programs part ia kg0000931 Chapter 1 introduction to computers, programs part ia
kg0000931 Chapter 1 introduction to computers, programs part ia
 
JavaYDL5
JavaYDL5JavaYDL5
JavaYDL5
 
bai giang java co ban - java cơ bản - bai 1
bai giang java co ban - java cơ bản - bai 1bai giang java co ban - java cơ bản - bai 1
bai giang java co ban - java cơ bản - bai 1
 
01slide
01slide01slide
01slide
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34
 
05slide
05slide05slide
05slide
 
Ppt on java basics1
Ppt on java basics1Ppt on java basics1
Ppt on java basics1
 
9781285852744 ppt ch02
9781285852744 ppt ch029781285852744 ppt ch02
9781285852744 ppt ch02
 
Exception handling
Exception handlingException handling
Exception handling
 
Java exception
Java exception Java exception
Java exception
 
Access Protection
Access ProtectionAccess Protection
Access Protection
 
ANDROID FDP PPT
ANDROID FDP PPTANDROID FDP PPT
ANDROID FDP PPT
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 

Similar to Exception handling

Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handlingKuntal Bhowmick
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in JavaAnkit Rai
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overviewBharath K
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024kashyapneha2809
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertionRakesh Madugula
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptionssaman Iftikhar
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJAYAPRIYAR7
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaKavitha713564
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-ivRubaNagarajan
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handlingAlpesh Oza
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handlingAlpesh Oza
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handlingAlpesh Oza
 
Itp 120 Chapt 18 2009 Exceptions & Assertions
Itp 120 Chapt 18 2009 Exceptions & AssertionsItp 120 Chapt 18 2009 Exceptions & Assertions
Itp 120 Chapt 18 2009 Exceptions & Assertionsphanleson
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handlingKuntal Bhowmick
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingSakkaravarthiS1
 

Similar to Exception handling (20)

Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
 
Exception handling
Exception handlingException handling
Exception handling
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.ppt
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
 
Itp 120 Chapt 18 2009 Exceptions & Assertions
Itp 120 Chapt 18 2009 Exceptions & AssertionsItp 120 Chapt 18 2009 Exceptions & Assertions
Itp 120 Chapt 18 2009 Exceptions & Assertions
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
 

Recently uploaded

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 

Recently uploaded (20)

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

Exception handling

  • 2. Throwing Exceptions  What is a good program? A program that is reliable?  Not just giving correct answer on correct input  Should protect against possible errors (invalid password, not a picture file, etc)
  • 3. Good programs  Need a robust program, reliable in the eyes of a novice user  It should not (“cannot”) crash easily - what if Word always crashed when you hit the control key?
  • 4. Good Programs  How do we ensure a robust program?  Option 1 – return a special value to determine if the method succeeded or failed  Ex. Make withdraw return true or false  What’s wrong with this?  Calling method may not check answer  Calling method may not know what to do
  • 5. Good Programs  Option 2 - Use exceptions  Exception – an error condition that can occur during the normal course of a program execution  Exception handling is another form of control structure (like ifs and switch statements)  When an error is encountered, the normal flow of the program is stopped and the exception is handled
  • 6. Exceptions  We say an exception is thrown when it occurs  When the exception-handling code is executed, the error is caught  Examples:  Dividing by zero  Accessing a null object
  • 7. Exceptions  What happens when exceptions occur?  An Exception object is thrown  What happens when an Exception is thrown?  normal execution stops and exception handling begins  What does the Exception object know?  the name of the problem  the location where it occurred  and more…
  • 8. Exceptions  Why use exceptions?  consistency (everyone else does it)  Java API classes use exceptions.  Other programming languages do too!  flexibility  programmer can decide how to fix problems.  simplicity  Easy to pinpoint problems.
  • 9. Handling Exceptions  Do nothing  program crashes if the exception occurs!  Propagate (throw) it  tell the method’s caller about it and let them decide what to do  Resolve (try-catch) it in our method  fix it or tell the user about it and let them decide what to do
  • 10. Handling Exceptions  So far, we have let the system handle exceptions int score = in.nextInt(); If the user enters “abc123” Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:819) at java.util.Scanner.next(Scanner.java:1431) at java.util.Scanner.nextInt(Scanner.java:2040) at java.util.Scanner.nextInt(Scanner.java:2000) at Test.main(Test.java:5)
  • 11. Handling Exceptions  Says in English:  System has caught an error described as a InputMismatchException  Thrown because a String cannot be converted to an integer  When system handles, we often get a program crash  Instead of the system, we can handle to improve robustness
  • 12. Handling Exceptions  Better solution: Instead of letting the program crash, use Exception Handling to improve program’s robustness  Exceptions cannot be ignored  Exceptions are handled by Exception Handlers directly
  • 13. Throwing Exceptions  If there is an error in the value of a parameter, we can throw exceptions to make the user accountable 1. Decide what type of exception to throw 2. Test for condition, and throw the exception if condition is violated
  • 14. Example  Throw an exception object to signal an exceptional condition  Example: What do we do if the amount to withdraw is greater than the balance?  IllegalArgumentException: illegal parameter value
  • 15. Problem public class BankAccount { public void withdraw(double amount) { if (amount > balance) { ????????? } balance = balance - amount; } . . . }
  • 16. Solution #1 public class BankAccount { public void withdraw(double amount) { if (amount > balance) { IllegalArgumentException exception = new IllegalArgumentException("Amount exceeds balance"); throw exception; } balance = balance - amount; } . . . }
  • 17. Solution #2 public class BankAccount { public void withdraw(double amount) { if (amount > balance) { throw new IllegalArgumentException("Amount exceeds balance"); } balance = balance - amount; } . . . }
  • 19. Checked/Unchecked Exceptions  Checked Exception – checked at compile time  Complier ensures that you are handling a possible problem  These errors are due to external circumstances that the programmer cannot prevent  Majority occur when dealing with input and output  For example, IOException
  • 20. Checked/Unchecked Exceptions  Unchecked Exception = Runtime Exceptions  Extend the class RuntimeException or Error  They are the programmer's fault  Examples of runtime exceptions:  NumberFormatException  IllegalArgumentException  NullPointerException  Optional to deal with these  Example of error: OutOfMemoryError  Can’t do anything about these catastrophic problems, so don’t deal with it
  • 21.
  • 22. Checked/Unchecked Exceptions  Unchecked Exceptions result from deficiencies in your code, so should check on own  Null object reference  Sending a negative value to Math.sqrt()  Checked Exceptions are not the fault of the coder  Problems with the file format, user input, etc.
  • 23. Checked/Unchecked Exceptions  Categories aren't perfect:  Scanner.nextInt throws unchecked InputMismatchException  Programmer cannot prevent users from entering incorrect input  This choice makes the class easy to use for beginning programmers
  • 24. Checked/Unchecked Exceptions  Deal with checked exceptions principally when programming with files and streams  For example, use a Scanner to read a file String filename = . . .; FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader);  But, FileReader constructor can throw a FileNotFoundException
  • 25. Handling Checked Exceptions 1. Handle the exception 2. Tell compiler that you want method to be terminated when the exception occurs  Use throws specifier so method can throw a checked exception public void read(String filename) throws FileNotFoundException { FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader); . . . }
  • 26. Handling Checked Exceptions  throws tells the compiler to “pass the buck” to the method that called this method  Can propagate multiple exceptions: public void read(String filename) throws IOException, ClassNotFoundException  Can also group using hierarchy  If method can throw an IOException and FileNotFoundException, only use IOException
  • 27. Handling Checked Exceptions  Why propagate when we could handle the error ourselves?  We may not know how to  Let user of my code decide  Better to declare exception than to handle it incompetently
  • 28. Catching Exceptions  At some point, an exception should be dealt with  If not, program terminates with error message  Professional code requires more sophistication – cannot just allow errors to kill program  What would happen if all of my.wisc.edu turned off if you entered wrong password?
  • 29. Catching Exceptions  To deal with this problem, install exception handlers in your code to deal with possible exceptions  Handlers are try/catch statements
  • 30. Try-Catch  Put statement(s) that could cause an error in the try block  Error handling code goes in catch block  Only is executed if there was an error  Can have multiple catch blocks, one for each possible type of exception
  • 31. try-catch Syntax try { <try block> } catch ( <ExceptionClass> <name> ) { <catch block> } catch ( <ExceptionClass> <name> ) { <catch block> }…
  • 32. try { String filename = . . .; FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader); String input = in.next(); int value = Integer.parseInt(input); . . . } catch (IOException exception) { exception.printStackTrace(); } catch (NumberFormatException exception) { System.out.println("Input was not a number"); }
  • 33. Example  3 types of error can be thrown  FileNotFoundException is thrown by FileReader constructor  caught by IOException clause  NoSuchElementException is thrown by Scanner.next  not caught, thrown to caller  NumberFormatException is thrown by Integer.parseInt()  caught by second clause
  • 34. Catching Exceptions  If there are no errors, the catch block is skipped  If an exception is thrown, the try block stops executing immediately and jumps to the catch block
  • 36. Exception Information  Why do we have Exception objects?  We can get information on where the error happened and what exactly happened  Exception objects have 2 methods defined:  getMessage() (what happened?)  printStackTrace() (where did it happen?)
  • 37. getMessage  Returns the data that cause the error  Example: … }catch(NumberFormatException e){ System.out.println(e.getMessage()); }
  • 38. printStackTrace  Prints out a trace of methods that caused the error starting at the root of the error  Where did the exception occur? What method called this code to execute..etc.  This is what the system does when an exception is thrown  Example: … }catch(NumberFormatException e){ e.printStackTrace(); }
  • 39. Catching ALL Exceptions public double average( String data ) { try { int sum = 0; for ( int i=0; i < data.length(); i++ ) sum += Integer.parseInt(data.charAt(i)); return sum/data.length(); } catch ( Exception e ) // catch ALL exceptions { System.out.println( e ); return 0; } }
  • 40. Catching ALL Exceptions  Why is this probably a bad idea?  Probably want to handle each type of exception differently  Don't want to catch things like NullPointerExeption
  • 41. Catching Exceptions  IMPORTANT! Order of catch blocks matters } catch (Exception e){ System.out.println(e.getMessage()); } catch (NumberFormatException e){ System.out.println("'" + str + "'not valid input, Please use digits only"); }  You should go specific to generic  NumberFormatException is a specific type of the class Exception (inheritance)
  • 42. Demo p.s.v. main( String [] args ) { try { String filename = args[0], input; scanner = new Scanner( new File(filename) ); input = scanner.nextLine(); int value = Integer.parseInt( input ); double reciprocal = 1.0 / value; System.out.println( "rec=" + rec ); } catch ( Exception e ) { S.o.pln( "Found Exception: " + e ); } S.o.pln( "Done" ); }
  • 43. String filename=args[0], input; try { scanner = new Scanner(new File(filename)); input = scanner.nextLine(); int value = Integer.parseInt( input ); double reciprocal = 1.0 / value; System.out.println( "rec=" + rec ); } catch ( NumberFormatException e ) { S.o.pln( input + " is not an integer"); } catch ( ArithmeticException e ) { S.o.pln( "Can't divide by zero" ); } catch ( FileNotFoundException e ) { S.o.pln( filename + " Not Found" ); } finally { S.o.pln( "Done" ); }
  • 44. Catching Exceptions  What if an exception is thrown and there is no catch block to match?  The system handles it (terminates program and prints the stack trace)
  • 45. The finally clause  Recall that whenever an exception occurs, we immediately go to the catch block  What if there is some code we want to execute regardless of whether there was an exception?  finally block is used
  • 46. The finally clause try{ distance = Double.parseDouble(str); if (distance < 0){ throw new Exception("Negative distance is not valid"); } return distance; } catch (NumberFormatException e){ System.out.println("'" + str + "'not valid input, Please use digits only"); } catch (Exception e){ System.out.println(e.getMessage()); } finally { System.out.println(“Done”); }
  • 47. The finally clause  finally is executed NO MATTER WHAT  Even if there is a break or return in the try block  Good for “cleanup” of a method
  • 48.
  • 49. Throwable Exception Inheritance Hierarchy Exception RuntimeException NullPointerException ArithmeticException NegativeArrayIndexException IndexOutOfBoundsException ArrayIndexOutOfBoundsException StringIndexOutOfBoundsException IllegalArgumentException NumberFormatException IOException FileNotFoundException EOFException
  • 50. try-catch Control Flow code before try try block no exceptions occur code after try
  • 51. try-catch Control Flow code before try exception occurs try block catch block code after try
  • 52. try-catch Control Flow code before try exception occurs try block catch block no exceptions occur code after try
  • 53. try-catch Control Flow code before try try block no exceptions occurred finally block (if it exists) code after try
  • 54. try-catch Control Flow code before try exception occurs try block catch block finally block (if it exists) code after try
  • 55. try-catch Control Flow exception occurs code before try true matches first try block catch block? no exceptions occurred 1st catch block false true matches next 2nd catch block catch block? false finally block (if it exists) code after try
  • 56. Propagating Exceptions  When a method may throw an exception, either directly or indirectly, we call the method an exception thrower.  Every exception thrower must be one of two types:  a catcher, or  a propagator.
  • 57. Propagating Exceptions  An exception catcher is an exception thrower that includes a matching catch block for the thrown exception.  An exception propagator does not contain a matching catch block.  A method may be a catcher of one exception and a propagator of another.
  • 58. Example  The following figure shows a sequence of method calls among the exception throwers.  Method D throws an instance of Exception. The green arrows indicate the direction of calls. The red arrows show the reversing of call sequence, looking for a matching catcher. Method B is the catcher.  The call sequence is traced by using a stack.
  • 60. Propagating Exceptions  If a method is an exception propagator, we need to modify its header to declare the type of exceptions the method propagates.  We use the reserved word throws for this declaration. public void C( ) throws Exception { ... } public void D( ) throws Exception { ... }
  • 61. Propagating Exceptions  Without the required throws Exception clause, the program will not compile.  However, for exceptions of the type called runtime exceptions, the throws clause is optional.
  • 62. Propagating vs. Catching  Do not catch an exception that is thrown as a result of violating a condition set by the client programmer.  Instead, propagate the exception back to the client programmer’s code and let him or her handle it.
  • 63. Exceptions in a Constructor  We can thrown an exception in the constructor if a condition is violated  For example, we may throw an IllegalArgumentException if a parameter value is invalid

Editor's Notes

  1. What exceptions can occur in this code fragment? NullPointerException ArithmeticException: / By Zero
  2. What exceptions can occur in this code fragment? IOException NumberFormatException ArithmeticException – DivideByZero NegativeArraySizeException
  3. What exceptions can occur in this code fragment? IOException NumberFormatException ArithmeticException – DivideByZero NegativeArraySizeException
  4. Create Exception Hierarchy Handout (online and hardcopy for class) Link to this for &quot;Java Exceptions&quot; web page.
  5. catch block must match the class of exception that occurs