How to throw Exceptions in Java?

Before you can catch an exception, some code somewhere must throw one. Any code can throw an exception: your code, code from a package written by someone else such as the packages that come with the Java platform, or the Java runtime environment. Regardless of what throws the exception, it's always thrown with the throw statement.

Java platform provides numerous exception classes. All the classes are descendants of the Throwable class, and all allow programs to differentiate among the various types of exceptions that can occur during the execution of a program.You can also create your own exception classes to represent problems that can occur within the classes you write.

The throw Statement

All methods use the throw statement to throw an exception. The throw statement requires a single argument: a throwable object. Throwable objects are instances of any subclass of the Throwable class. Here's an example of a throw statement.

Code: Java

throw someThrowableObject;

If you want to throw an exception explicitly then you need to use the throw clause. All the system-defined exceptions are thrown automatically, but the user-defined exceptions must be thrown explicitly using the throw clause. It takes the form as:

The UserDefinedException is a class made specifically to handle an exception and it is encapsulating some specific kind of user defined behaviour. This exception is raised explicitly using the throw clause. At the same time the catch clause is there ready to catch the same exception object.

Consider the following example in which a system defined exception is deliberately thrown in order to demonstrate the functionality of the throw clause:

In the above example the throw clause throws an object of a system defined exception NullPointerException, which is actually thrown when an object storing a null pointer is reference. Thus, as soon as an the exception is raised it is caught with the catch clause, the statement inside the catch clause are executed and we get the above output.