There are times when it makes sense for a program to deliberately throw an exception. This is the case when the program discovers some sort of exception or error condition, but there is no reasonable way to handle the error at the point where the problem is discovered. The program can throw an exception in the hope that some other part of the program will catch and handle the exception.
- To throw an exception use a
throw
statement. This is usually done with an if statement. The syntax of the throw statement is:
throw exception-object;
For example, the following statement throws an ArithmeticException
:
if(number == 0){
throw new ArithmeticException("Division by zero");
}
The exception object is created with the new operator right in the throw
statement. Exception classes in Java have a default constructor that takes no arguments and a constructor that takes a single String
argument. If provided, this String
appears in the exception message when the exception occurs.