CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ

Validate

Validate input data
Handle exceptions
Exception-throwing code<

the compiler does NOT pay attention to exceptions that are of type RuntimeException. A RuntimeException does not have to be declared or wrapped in a try/catch.

When you write code that could throw an exception, you must declare the exception.

An exception is an object of type Exception.

Risky, exception-throwing code

// this method must tell the world that it throws a BadException
public void takeRisk() throws BadException {
	if (abandonAllHope) {
		// Create a new Exception object and throw it
		throw new BadException();
	}
}

Your code that calls the risky method

public void crossFingers() {
	try {
		anObject.takeRisk();
	}
	catch (BadException e) {
		System.out.println("Sorry Invalid input");
		// All exceptions inherit a printStackTrace() method
		e.printStackTrace();
	}
}
Previous | How exceptions work | How to catch exceptions | Application | Exception-throwing code | Next