Throwing an Exception

Contact Us or call 1-877-932-8228
Throwing an Exception

Throwing an Exception

The keyword throw is used to trigger the exception-handling process (or, "raise" the exception, as it is often termed in other languages).

That word is followed by an instance of a throwable object, i.e., an instance of a class that extends Throwable. Usually, a new instance of an appropriate exception class is created to contain information about the exception.

For example, suppose a setAge() method expects a nonnegative integer; we can have it throw an IllegalArgumentException if it receives a negative value. It makes sense for the method that calls setAge() to do something about the problem, since it is where the illegal number came from.

So, we can declare setAge() as throws IllegalArgumentException.

public void setAge(int age) throws IllegalArgumentException {
	if (age < 0) 
		throw new IllegalArgumentException("Age must be >= 0");
		this.age = age;