Exception Classes

Download Report

Transcript Exception Classes

Exception Handling
Part 2: Creating and Throwing Exceptions
CSIS 3701: Advanced Object Oriented Programming
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
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!
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”
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
Defining Exception Classes
• Examples:
public class FullListException
extends RuntimeException {
}
FullListException.java
public class InListException
extends RuntimeException {
}
InListException.java
Throwing Exceptions
• Basic syntax:
throw new exceptiontype();
Construct new exception object
And throw it back to caller
• Note: Method exited at this point
and nothing returned
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 {
…
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++;
}
Throwing Exceptions
• Examples:
public NameList(int max)
throws NegativeListException {
if (max <= 0) throw new NegativeListException();
maximum = max;
current = 0;
names = new String[maximum];
}
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
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;}
}
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
Adding Information to Exceptions
• Caller can use methods to retrieve information:
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
try {
Call method on exception
names.add(name);
object to get information
…
}
catch (InListException ex) {
String duplicate = ex.getName();
JOptionPane.showMessageDialog(this,
duplicate + " already in list");
}
Exception Class Hierarchy
• Java defines two types of
exception
– Exception
– RuntimeException
(which extends
Exception)
• Most commonly used
exceptions extend
RuntimeException
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”);
}
Opening a file might
catch (IOException ex) {
cause IOExeception if
file does not exist, etc.
…
Must be caught
}
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.
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