SLIDE 2 9/6/20 2
§ To handle an exception, the
line that throws the exception is executed within a try block
§ A try block is followed by one
§ When an exception occurs,
processing continues at the first catch clause that matches the exception type
1-3
// here is code that // here is code that // should generate no exceptions // should generate no exceptions try try { // code to monitor // code to monitor // several possible things // several possible things // that can go wrong // that can go wrong // goes here // goes here } catch catch (ExceptionTypeA ExceptionTypeA ex) { ex) { //handler for //handler for ExceptionTypeA ExceptionTypeA } catch catch (ExceptionTypeB ExceptionTypeB ex) { ex) { //handler for //handler for ExceptionTypeB ExceptionTypeB } // after a catch, continue here // after a catch, continue here
3
try { zone = code.charAt(9); district = Integer.parseInt(code.substring(3, 7)); valid++; if (zone == 'R' && district > 2000) banned++; } catch (StringIndexOutOfBoundsException exception) { System.out.println ("Improper code length: " + code); } catch (NumberFormatException exception) { System.out.println ("District is not numeric: " + code); }
// Counts the number of product codes that are entered // with a zone of R and district greater than 2000.
D I S T Z
4