You know that Java uses the throw and try-catch mechanism for handling exceptions as described in the tutorial Getting Started with Exception Handling in Java.

In this Java tutorial, I’m going to tell you how to write code that declares to throw exceptions. This involves in using the throw and throws keywords together.

 

1. How to throw an exception?

Consider the following class:

public class Engineer {

	protected int age;

	public void setAge(int age) {
		this.age = age;
	}
}
We want to ensure that the age of an engineer is always in a valid range, e.g. between 21 and 59. To do so, we can check the parameter age and throw an exception if it is out of range. Hence, we update the setAge() method as following:

public void setAge(int age) {
	if (age < 21 || age > 59) {
		throw new IllegalArgumentException("Invalid age");
	}
	this.age = age;
}
Here, the throwkeyword is used to throw a new exception object if the passed-in parameter has invalid value. When the statement started by the throw keyword gets executed, the current method stops its execution and control returned to the caller code which can have an exception handler.

The following is a test program that uses try-catch structure to handle the above exception:

public class EngineerTest {
	public static void main(String[] args) {

		int age = Integer.parseInt(args[0]);

		try {

			Engineer newEngineer = new Engineer();

			newEngineer.setAge(age);

		} catch (IllegalArgumentException ex) {
			System.err.println(ex);
		}
	}
}
This program tries to create a new Engineer object with age is passed from the command-line argument. Note that in the catch block, we use the System.err static class to print out the exception object. It represents the error console, which differs from the output console represented by the System.out static class.

Run the test program with the following command:

java EngineerTest 65


This gives the following output:

java.lang.IllegalArgumentException: Invalid age
Why? It’s because the setAge() throws IllegalArgumentException as the age is not in a valid range.

The above examples show you how to use the throwkeyword to throw an exception in your code. And which kind of exceptions can you throw?

Read on as I’m about to explain in the next section.

 

2. Specify exceptions to be thrown in a method

How do we know whether a method can throw exceptions or not? And how do we know which exceptions does a method throw?

The answer is, by looking for the throwsclause in the method’s signature. For example:

public int read() throws IOException
I take this method from the InputStreamReader class in the java.io package. The throws clause contains one more exceptions (separated by commas) which can be thrown in the method’s body.

Here, the read() method can throw IOException while reading data from a file.

So we know that the throws keyword is used in method’s signature to specify exceptions can be thrown. Remember these rules:

So you know that the throwand throwskeywords are used together in a method to throw and declare to throw exceptions. The following example shows a method that declares to throw a checked exception:

public int divide(int a, int b) throws Exception {
	if (b == 0) {
		throw new Exception("Cannot be divided by zero");
	}

	return a / b;
}
Here, the divide() method declares to throw an Exception if the parameter b equals to 0. Note that throwing a general exception (here Exception is the base class of all exceptions) is discouraged. In practice, we should throw more specific exceptions.

 

3. Some rules regarding throw and throws:

Remember the following rules:

 

Other Java Exception Handling Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.