Besides catching exceptions thrown by Java, a program can throw its own exceptions, declare them, and define new exception types for its own rules.
The throw Statement
The throw statement throws an exception explicitly: throw new ArithmeticException("invalid amount");. It takes an object of Throwable or a subclass. Execution of the current block stops at once, and the exception travels to the nearest matching catch. throw is used to report a violation of the program's own rules, such as a negative balance, or to re-throw a caught exception.
Definition: User-defined exception. An exception class written by the programmer, usually by extending Exception or RuntimeException, to represent an error condition specific to the application.
The throws Clause
A method that may throw a checked exception that it does not handle must declare it with throws in its header: void readFile() throws IOException { ... }. This warns callers, who must then catch the exception or declare it in turn. A method may declare several exceptions, separated by commas. Unchecked exceptions need not be declared. The difference is: throw is a statement that actually throws one exception object; throws is part of a method declaration that lists the exceptions the method may throw.
User-Defined Exceptions
Java's built-in exceptions cannot describe every application error, so programmers can create their own. A user-defined exception is a class that extends Exception (for a checked exception) or RuntimeException (for an unchecked one). It usually has a constructor that takes a message and passes it to the superclass with super(message), and it may override toString() to give a custom description, which is what println shows when the exception object is printed. The exception is thrown with throw and caught like any other. Examples are InsufficientBalanceException, InvalidMarksException and UnderAgeException.
Validating Input with Exceptions
A common use is to check data. A method test(int age) throws UnderAge if the age is below 18, and the caller catches it and prints a message. Another is to reject duplicate numbers in a list by throwing an exception when a value is seen twice.
Table 4.5: throw and throws
| Feature | throw | throws |
|---|---|---|
| Kind | Statement | Clause in method header |
| Purpose | Throws one exception | Declares possible exceptions |
| Followed by | An exception object | Exception class names |
| Example | throw new UnderAge(15); | void test() throws UnderAge |
Example 4.5: The UnderAge exception
Problem: Create an exception UnderAge that prints "Under Age" with the age when printed. Write test(int age), which throws UnderAge if age < 18, and call it with ages 21 and 15.
Solution:
- class UnderAge extends Exception, storing the age and overriding toString().
- static void test(int age) throws UnderAge { if (age < 18) throw new UnderAge(age); ... }.
- In main, call test inside try, and print the exception in catch.
Result: Age 21 is accepted; age 15 prints "Under Age: 15".
public class ExceptionDemo {
static void test(int age) throws UnderAge {
if (age < 18) throw new UnderAge(age);
System.out.println("Age " + age + " accepted");
}
public static void main(String[] args) {
int[] ages = {21, 15};
for (int a : ages) {
try {
test(a);
} catch (UnderAge e) {
System.out.println(e);
}
}
}
}
class UnderAge extends Exception {
private int age;
UnderAge(int age) { super("age too low"); this.age = age; }
@Override public String toString() { return "Under Age: " + age; }
}
Output
Age 21 accepted
Under Age: 15
Common mistakes
- Confusing throw (a statement) with throws (a declaration).
- Throwing a checked exception without declaring it with throws.
- Extending Error instead of Exception for an application exception.
Key takeaways
- throw throws an exception object explicitly.
- throws declares the checked exceptions a method may throw.
- User-defined exceptions extend Exception or RuntimeException.
- Override toString() or pass a message to super() to describe the error.
Practice questions
- Distinguish throw and throws.
- How is a user-defined checked exception created?
- Must a method declare an unchecked exception that it throws?
Answers to the practice questions
- throw is a statement that throws an exception object; throws is a clause that declares the exceptions a method may throw.
- By writing a class that extends Exception.
- No; only checked exceptions must be declared.
Sources
- Official BCA syllabus Object Oriented Programming using Java, course code 25BCA402SEC01, Unit IV
