Java Exception Handling Dealing with errors using Javas
- Slides: 61
Java Exception Handling Dealing with errors using Java’s exception handling mechanism James Tam
Approaches For Dealing With Error Conditions Use conditional statements and return values Use Java’s exception handling mechanism James Tam
Class Inventory: An Earlier Example class Inventory { private int stock. Level = 0; public boolean add. To. Inventory (int amount) { final int MAX = 100; int temp; temp = stock. Level + amount; if (temp > MAX) { System. out. print("Adding " + amount + " item will cause stock "); System. out. println("to become greater than " + MAX + " units (overstock)"); return false; } James Tam
Class Inventory: An Earlier Example (2) else { stock. Level = stock. Level + amount; return true; } } // End of method add. To. Inventory : James Tam
Some Hypothetical Method Calls: Condition/Return object 1. method 1 () if (object 2. method 2() == false) return false; object 2. method 2 () if (store. add. To. Inventory(amt) == false) return false; store. add. To. Inventory (int amt) if (temp > MAX) return false; James Tam
Some Hypothetical Method Calls: Condition/Return object 1. method 1 () if (object 2. method 2() == false) return false; Problem 1: The calling method may forget to check the return value object 2. method 2 () if (store. add. To. Inventory(amt) == false) return false; store. add. To. Inventory (int amt) if (temp > MAX) return false; James Tam
Some Hypothetical Method Calls: Condition/Return object 1. method 1 () if (object 2. method 2() == false) return false; object 2. method 2 () if (store. add. To. Inventory(amt) == false) return false; Problem 2: A long series of method calls requires many checks/returns store. add. To. Inventory (int amt) if (temp > MAX) return false; James Tam
Some Hypothetical Method Calls: Condition/Return object 1. method 1 () if (object 2. method 2() == false) return false; object 2. method 2 () if (store. add. To. Inventory(amt) == false) ? ? Problem 3: The calling method may not know how to handle the error return false; ? ? store. add. To. Inventory (int amt) if (temp > MAX) return false; James Tam
Approaches For Dealing With Error Conditions Use conditional statements and return values Use Java’s exception handling mechanism James Tam
Handling Exceptions Format: try { // Code that may cause an error/exception to occur } catch (Exception. Type identifier) { // Code to handle the exception } James Tam
Handling Exceptions: Reading Input The complete program can be found in the directory: /home/233/examples/exceptions/handling. Exceptions/input. Example import java. io. *; class Driver { public static void main (String [] args) { Buffered. Reader string. Input; Input. Stream. Reader character. Input; String s; int num; character. Input = new Input. Stream. Reader(System. in); string. Input = new Buffered. Reader(character. Input); James Tam
Handling Exceptions: Reading Input (2) try { System. out. print("Type an integer: "); s = string. Input. read. Line(); System. out. println("You typed in. . . " + s); num = Integer. parse. Int (s); System. out. println("Converted to an integer. . . " + num); } catch (IOException e) { System. out. println(e); } catch (Number. Format. Exception e) { : : : } } } James Tam
Handling Exceptions: Where The Exceptions Occur try { System. out. print("Type an integer: "); s = string. Input. read. Line(); System. out. println("You typed in. . . " + s); num = Integer. parse. Int (s); System. out. println("Converted to an integer. . . " + num); } James Tam
Handling Exceptions: Result Of Calling Read. Line () try { System. out. print("Type an integer: "); The first exception s = string. Input. read. Line(); can occur here System. out. println("You typed in. . . " + s); num = Integer. parse. Int (s); System. out. println("Converted to an integer. . . " + num); } James Tam
Where The Exceptions Occur In Class Buffered. Reader For online documentation for this class go to: http: //java. sun. com/j 2 se/1. 4. 1/docs/api/java/io/Buffered. Reader. html Class Buffered. Reader { public Buffered. Reader (Reader in); public Buffered. Reader (Reader in, int sz); public String read. Line () throws IOException; : } James Tam
Handling Exceptions: Result Of Calling Parse. Int () try { System. out. print("Type an integer: "); s = string. Input. read. Line(); System. out. println("You typed in. . . " + s); The second exception num = Integer. parse. Int (s); can occur here System. out. println("Converted to an integer. . . " + num); } James Tam
Where The Exceptions Occur In Class Integer For online documentation for this class go to: http: //java. sun. com/j 2 se/1. 4. 1/docs/api/java/lang/Integer. html class Integer { public Integer (int value); public Integer (String s) throws Number. Format. Exception; : : public static int parse. Int (String s) throws Number. Format. Exception; : : } James Tam
Handling Exceptions: The Details try { System. out. print("Type an integer: "); s = string. Input. read. Line(); System. out. println("You typed in. . . " + s); num = Integer. parse. Int (s); System. out. println("Converted to an integer. . . " + num); } catch (IOException e) { System. out. println(e); } catch (Number. Format. Exception e) { : : : } } } James Tam
Handling Exceptions: Tracing The Example Integer. parse. Int (String s) { : : Driver. main () } try { num = Integer. parse. Int (s); } : catch (Number. Format. Exception e) { : } James Tam
Handling Exceptions: Tracing The Example Integer. parse. Int (String s) { Oops! The user didn’t enter an integer Driver. main () } try { num = Integer. parse. Int (s); } : catch (Number. Format. Exception e) { : } James Tam
Handling Exceptions: Tracing The Example Integer. parse. Int (String s) { Number. Format. Exception e = new Number. Format. Exception (); Driver. main () } try { num = Integer. parse. Int (s); } : catch (Number. Format. Exception e) { : } James Tam
Handling Exceptions: Tracing The Example Integer. parse. Int (String s) { Number. Format. Exception e = new Number. Format. Exception (); Driver. main () } try { num = Integer. parse. Int (s); } : catch (Number. Format. Exception e) { : } James Tam
Handling Exceptions: Tracing The Example Integer. parse. Int (String s) { Driver. main () } try { num = Integer. parse. Int (s); } : catch (Number. Format. Exception e) { Exception must be dealt with here } James Tam
Handling Exceptions: Catching The Exception catch (Number. Format. Exception e) { System. out. println(e); } } } James Tam
Catching The Exception: Error Messages catch (Number. Format. Exception e) { System. out. println(e. get. Message()); System. out. println(e); e. print. Stack. Trace(); } } } James Tam
Catching The Exception: Error Messages catch (Number. Format. Exception e) For input string: "james tam" { System. out. println(e. get. Message()); System. out. println(e); e. print. Stack. Trace(); } java. lang. Number. Format. Exception: For input string: "james tam" } } java. lang. Number. Format. Exception: For input string: "james tam" at java. lang. Number. Format. Exception. for. Input. String(Number. Format. Exception. java: 48) at java. lang. Integer. parse. Int(Integer. java: 426) at java. lang. Integer. parse. Int(Integer. java: 476) at Driver. main(Driver. java: 39) James Tam
Categories Of Exceptions • Unchecked exceptions • Checked exception James Tam
Characteristics Of Unchecked Exceptions • The compiler doesn’t require you to handle them if they are thrown. • No try-catch block required by the compiler • They can occur at any time in the program (not just for a specific method) • Typically they are fatal runtime errors that are beyond the programmer’s control • Use conditional statements rather than the exception handling model. • Examples: • Null. Pointer. Exception, Index. Out. Of. Bounds. Exception, Arithmetic. Exception… James Tam
Common Unchecked Exceptions: Null. Pointer. Exception int [] arr = null; arr[0] = 1; Null. Pointer. Exception arr = new int [4]; int i; for (i = 0; i <= 4; i++) arr[i] = i; arr[i-1] = arr[i-1] / 0; James Tam
Common Unchecked Exceptions: Array. Index. Out. Of. Bounds. Exception int [] arr = null; arr[0] = 1; arr = new int [4]; int i; for (i = 0; i <= 4; i++) arr[i] = i; Array. Index. Out. Of. Bounds. Exception (when i = 4) arr[i-1] = arr[i-1] / 0; James Tam
Common Unchecked Exceptions: Arithmetic. Exceptions int [] arr = null; arr[0] = 1; arr = new int [4]; int i; for (i = 0; i <= 4; i++) arr[i] = i; arr[i-1] = arr[i-1] / 0; Arithmetic. Exception (Division by zero) James Tam
Checked Exceptions Must be handled if the potential for an error exists • You must use a try-catch block Deal with problems that occur in a specific place • When a particular method invoked enclose it within a try-catch block Example: • Number. Format. Exception, IOException James Tam
Avoid Squelching Your Exceptions try { s = string. Input. read. Line(); num = Integer. parse. Int (s); } catch (IOException e) { System. out. println(e); } catch (Number. Format. Exception e) { // Do nothing here but set up the try-catch block to bypass the // annoying compiler error } James Tam
Avoid Squelching Your Exceptions try { NO! s = string. Input. read. Line(); num = Integer. parse. Int (s); } catch (IOException e) { System. out. println(e); } catch (Number. Format. Exception e) { // Do nothing here but set up the try-catch block to bypass the // annoying compiler error } James Tam
The Finally Clause • An additional part of Java’s exception handling model (trycatch-finally). • Used to enclose statements that must always be executed whether or not an exception occurs. James Tam
The Finally Clause: Exception Thrown Foo. method () try { f. method(); { } } catch { } finally { } James Tam
The Finally Clause: Exception Thrown try { te the at u c e x k th to e c t o p l b m y 1) Atte od in the tr eption meth ow an exc hr may t f. method(); Foo. method () { 2) Exception thrown here } } catch { n is o i t ep here c x t 3) E augh c } finally { 4) A the end of the catch block control transfers to the finally clause } James Tam
The Finally Clause: No Exception Thrown try { te the at u c e x k th to e c t o p l b m y 1) Atte od in the tr eption meth ow an exc hr may t f. method(); Foo. method () { 2) Code runs okay here } } catch { } finally { ol r t on ally f c o ) nd od ( e fin e h h the met to t A. s 3) Foo sfer n tra use cla } James Tam
Try-Catch-Finally: An Example The complete program can be found in the directory: /home/233/examples/exceptions/handling. Exceptions/ try. Catch. Finally. Example class Driver { public static void main (String [] args) { TCFExample eg = new TCFExample (); eg. method(); } } James Tam
Try-Catch-Finally: An Example (2) class TCFExample { public void method () { Buffered. Reader br; String s; int num; try { System. out. print("Type in an integer: "); br = new Buffered. Reader(new Input. Stream. Reader(System. in)); s = br. read. Line(); num = Integer. parse. Int(s); return; } James Tam
Try-Catch-Finally: An Example (3) catch (IOException e) { e. print. Stack. Trace(); return; } catch (Number. Format. Exception e) { e. print. Stack. Trace (); return; } finally { System. out. println("<<<This code will always execute>>>"); return; } } } James Tam
When The Caller Can’t Handle The Exceptions method 2 () Exception thrown! method 1 () ? ? ? main () James Tam
When The Caller Can’t Handle The Exceptions: An Example The complete program can be found in the directory: /home/233/examples/exceptions/handling. Exceptions/ delegating. Exceptions class Driver { public static void main (String [] args) { TCExample eg = new TCExample (); try { eg. method(); } James Tam
When The Caller Can’t Handle The Exceptions: An Example (2) catch (IOException e) { e. print. Stack. Trace(); } catch (Number. Format. Exception e) { e. print. Stack. Trace(); } } } James Tam
When The Caller Can’t Handle The Exceptions: An Example (3) import java. io. *; class TCExample { public void method () throws IOException, Number. Format. Exception { Buffered. Reader br; String s; int num; System. out. print("Type in an integer: "); br = new Buffered. Reader(new Input. Stream. Reader(System. in)); s = br. read. Line(); num = Integer. parse. Int(s); } } James Tam
When The Main () Method Can’t Handle The Exception class Driver 2 { public static void main (String [] args) throws IOException, Number. Format. Exception { TCExample eg = new TCExample (); eg. method(); } } James Tam
Creating Your Own Exceptions Throwable Error Virtual. Machine. Error Exception … IOException … ? ? ? Run. Time Exception Out. Of. Memory. Error James Tam
Class Exception: The Local Inheritance Hierarchy Exception Class. Not. Found IOException Clone. Not. Found Exception EOFException File. Not. Found Malformed. URL Unknown. Host Exception James Tam
Writing New Exceptions: An Example The full example can be found in the directory: /home/233/examples/exceptions/writing. Exceptions/inventory. Example James Tam
Writing New Exceptions: The Driver Class class Driver { public static void main (String [] args) { Inventory chinook. Inventory = new Inventory (); char menu. Option; int amount; boolean temp; do { System. out. println("nn. INVENTORY PROGRAM: OPTIONS"); System. out. println("t(A)dd new stock to inventory"); System. out. println("t(R)emove stock from inventory"); System. out. println("t(D)isplay stock level"); System. out. println("t(C)heck if stock level is critical"); System. out. print("t(Q)uit program"); System. out. println(); James Tam
Writing New Exceptions: The Driver Class (2) System. out. print("Selection: "); menu. Option = (char) Console. in. read. Char(); Console. in. read. Line(); System. out. println(); switch (menu. Option) { case 'A': System. out. print("No. items to add: "); amount = Console. in. read. Int(); Console. in. read. Char(); James Tam
Writing New Exceptions: The Driver Class (3) try { chinook. Inventory. add. To. Inventory(amount); } catch (Inventory. Over. Max. Exception e) { e. print. Stack. Trace(); } finally { chinook. Inventory. display. Inventory. Level(); break; } James Tam
Writing New Exceptions: The Driver Class (4) case 'R': System. out. print("No. items to remove: "); amount = Console. in. read. Int(); Console. in. read. Char(); try { chinook. Inventory. remove. From. Inventory(amount); } catch (Inventory. Below. Min. Exception e) { e. print. Stack. Trace(); } finally { chinook. Inventory. display. Inventory. Level(); break; } James Tam
Writing New Exceptions: The Driver Class (5) case 'D': chinook. Inventory. display. Inventory. Level(); break; case 'C': temp = chinook. Inventory. inventory. Too. Low(); if (chinook. Inventory. inventory. Too. Low()) System. out. println("Stock levels critical!"); else System. out. println("Stock levels okay"); chinook. Inventory. display. Inventory. Level(); break; case 'Q': System. out. println("Quitting program"); break; James Tam
Writing New Exceptions: The Driver Class (6) default: System. out. println("Enter one of A, R, D, C or Q"); } } while (menu. Option != 'Q'); } } James Tam
The Inventory Class class Inventory { public final static int CRITICAL = 10; public final static int MIN = 0; public final static int MAX = 100; private int stock. Level; // Method definitions public void add. To. Inventory (int amount) throws Inventory. Over. Max. Exception { int temp; temp = stock. Level + amount; if (temp > MAX) { throw new Inventory. Over. Max. Exception ("Adding " + amount + " item will cause stock to become greater than " + MAX + " units"); } James Tam
The Inventory Class (2) else { stock. Level = stock. Level + amount; } } public void remove. From. Inventory (int amount) throws Inventory. Below. Min. Exception { int temp; temp = stock. Level - amount; if (temp < MIN) { throw new Inventory. Below. Min. Exception ("Removing " + amount + " item will cause stock to become less than " + MIN + " units"); } James Tam
The Inventory Class (3) else { stock. Level = temp; } } public boolean inventory. Too. Low () { if (stock. Level < CRITICAL) return true; else return false; } public void display. Inventory. Level () { System. out. println("No. items in stock: " + stock. Level); } } James Tam
Class Inventory. Over. Max. Exception class Inventory. Over. Max. Exception extends Exception { public Inventory. Over. Max. Exception () { super (); } public Inventory. Over. Max. Exception (String s) { super (s); } } James Tam
Class Inventory. Below. Min. Exception class Inventory. Below. Min. Exception extends Exception { public Inventory. Below. Min. Exception () { super(); } public Inventory. Below. Min. Exception (String s) { super(s); } } James Tam
You Should Now Know • The benefits of handling errors with an exception handler rather than employing a series of return values and conditional statements. • How to handle exceptions • Being able to call a method that may throw an exception by using a try-catch block • What to do if the caller cannot properly handle the exception • What is the finally clause, how does it work and when should it be used • What is the difference between a checked an unchecked exception • How to write your classes of exceptions James Tam
- Switch case javas
- Exception handling in java
- Exception handling pada java
- Exception handling pada java
- Contoh error handling
- Exception handling in vb net
- Throw exception php
- Fiq irq
- Exception handling in ada
- Php exception
- Vb.net error handling
- Extends and implements difference
- Java exception checked vs unchecked
- Exception vs error in java
- Java exception hierarchy
- Java exception error
- Java unchecked exception
- Java exception localized message
- Java unchecked exception
- Gui event handling
- Assimilation linguistics
- Examples of abiotic factors
- Section 2 dealing with other nations
- Call center stress
- Dealing with competition marketing management
- It is a genre of speculative
- Chapter 5 lesson 1 dealing with anxiety and depression
- Chapter 5 lesson 1 dealing with anxiety and depression
- Dealing with competition marketing management
- Unit 1 dealing with incoming calls
- Dealing with anger in the bible
- Dealing successfully with difficult changes in your life
- Lexicological unit
- A play dealing with unhappy ending
- Dealing with unstructured data
- Reuters dealing tutorial
- Dealing with unstructured data
- The branch of zoology dealing with insects
- The branch of zoology dealing with insects
- Dealing with challenging patients
- Dealing successfully with difficult changes
- Dealing with unstructured data
- Alan linning
- Resolve complaint
- 3p fair dealing
- Constant synoynm
- Objection prix addition soustraction
- A.s environs ltd is dealing in environment
- A nation's overall plan for dealing
- Difficult volunteers
- System argument exception
- Public interface foo
- Class a void foo() throws exception
- Unt pcard exception form
- Coccus
- Runtimeexception extends exception
- What is exception?
- Explain the exceptions to mendel's law
- Charting by exception pros and cons
- Exception of koch postulates
- Apa itu exception
- Goodsalls rule