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:

  • If code in the method can throw checked exceptions, the method must declare to throw those exceptions in its signature, otherwise we will get compile error. And the caller code should handle those exceptions.  

  • If code in the method can throw unchecked exceptions, the method is not required to declare to throw those exceptions. That’s why in the Engineer example above, the setAge() method does not declare to throw IllegalArgumentException which is an unchecked exception. And the caller code can choose to handle unchecked exceptions or not.
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:

  • If code in a method throws checked exceptions, the method must specify those exceptions in the throws clause.
  • Unchecked exceptions are not required to be caught or declared.  

  • The exceptions specified in the throws clause can be broader than the ones can be thrown in the method’s body. Here’s an example:
    public void deleteDir(String path) throws IOException {
    	if (path == null) {
    		throw new FileNotFoundException("Directory not found");
    	}
    	// code to delete...
    }
     

    Here, code in the method can throw FileNotFoundException but the method declares to throw IOException. This is possible because IOException is the parent class of FileNotFoundException.

  • A method can declare to throw exceptions although its code doesn’t throw any exceptions. This is possible because the code can throw exceptions when it involves in the future. Here’s an example:
    public void encryptFile(String path) throws IOException {
    	// no exceptions thrown here...
    }
  • Constructors can throw exceptions and declare to throw exceptions just like normal methods.  

  • We can also specify exceptions can be thrown by methods in an interface.
 

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.



Add comment

   


Comments 

#1Rajeswaran R2022-10-30 10:06
It's really useful. Thanks
Quote