Presentation is loading. Please wait.

Presentation is loading. Please wait.

Exception Handling Part 2: Creating and Throwing Exceptions CSIS 3701: Advanced Object Oriented Programming.

Similar presentations


Presentation on theme: "Exception Handling Part 2: Creating and Throwing Exceptions CSIS 3701: Advanced Object Oriented Programming."— Presentation transcript:

1 Exception Handling Part 2: Creating and Throwing Exceptions CSIS 3701: Advanced Object Oriented Programming

2 Validation and Exceptions Key validation question: How should your methods handle invalid states? –Prevent state change –Notify user Best approach: Throw custom exceptions –Define new exception classes –Throw when problems detected in your code

3 Designing Exceptions Key question: What can go wrong? NameList example: –User can add new name to full list –User can add name already in list –User can access name at nonexistent index User will get ArrayIndexOutOfBoundsException if you don’t handle! –User can construct list with non-positive size Constructors can also throw exceptions!

4 New Exception Classes –User can add new name to full list  FullListException –User can add name already in list  InListException –User can access name at nonexistent index  BadIndexException –User can construct list with non-positive size  NegativeListException General convention: all exception classes end with “ Exception ”

5 Defining Exception Classes Each exception type is a new class –Must (usually) extend RuntimeException Usually have no methods or constructors –Simply act as “flag” to throw or catch public class myexceptionException extends RuntimeException { } myexceptionException.java

6 Defining Exception Classes Examples: public class FullListException extends RuntimeException { } FullListException.java public class InListException extends RuntimeException { } InListException.java

7 Throwing Exceptions Basic syntax: throw new exceptiontype(); Note: Method exited at this point and nothing returned Construct new exception object And throw it back to caller

8 Throwing Exceptions Can put exception type thrown in header –Not required (except in some cases) –Very good practice Allows users to easily see what kind of exceptions hey may need to handle public returntype methodname(parameters) throws exceptiontype { …

9 Throwing Exceptions Example: public void add(String name) throws FullListException, InListException { if (isFull()) throw new FullListException(); if (isIn(name)) throw new InListException(); names[current] = name; current++; }

10 Throwing Exceptions Examples: public NameList(int max) throws NegativeListException { if (max <= 0) throw new NegativeListException(); maximum = max; current = 0; names = new String[maximum]; }

11 Catching and Throwing Exceptions Often catch one type of exception and then throw another type public String getNameByIndex(int index) throws BadIndexException { try {return names[index];} catch (ArrayIndexOutOfBoundsException ex) { throw new BadIndexException(); } } Adds to encapsulation of internal representation –If changed, that exception type may no longer be thrown

12 Adding Information to Exceptions Exception objects can contain information –Stored as member variables –Set by constructor when exception thrown –Accessed via methods when exception caught public class InListException extends RuntimeException { private String name; public InListException(String n) {name = n;} public String getName() {return name;} }

13 Adding Information to Exceptions Method uses constructor to set properties: public void add(String name) throws FullListException, InListException { if (isFull()) throw new FullListException(); if (isIn(name)) throw new InListException(name); names[current] = name; current++; } Information passed to constructor, stored in state variable

14 Adding Information to Exceptions Caller can use methods to retrieve information: public void actionPerformed(ActionEvent e) { String name = nameField.getText(); try { names.add(name); … } catch (InListException ex) { String duplicate = ex.getName(); JOptionPane.showMessageDialog(this, duplicate + " already in list"); } Call method on exception object to get information

15 Exception Class Hierarchy Java defines two types of exception –Exception –RuntimeException (which extends Exception ) Most commonly used exceptions extend RuntimeException

16 Exception Class Hierarchy Subclasses of Exception must be handled –Any statement that might cause one of these exceptions must be inside try/catch block –Code will not compile otherwise Example: File commands might cause IOException try { File f = new File(“stuff.txt”); } catch (IOException ex) { … } Opening a file might cause IOExeception if file does not exist, etc. Must be caught

17 Exception Class Hierarchy Theory vs. Practice –Theory: Any statement that might cause exception should be in try/catch block –Practice: Would need to put almost every statement in try/catch block Any use of object could cause NullPointerException, etc.

18 Exception Class Hierarchy Compromise: –Only require handling for exceptions that might affect memory external to program Files/Networking: IOException Databases: SQLException Client/Server: ServletException –Problems that cannot be restricted to JVM Design note: –Your exception classes should extend RuntimeException


Download ppt "Exception Handling Part 2: Creating and Throwing Exceptions CSIS 3701: Advanced Object Oriented Programming."

Similar presentations


Ads by Google