Java throw

Sometimes it is required in the code to throw an exception deliberately. In order to achieve the same, the Java throw keyword should be used. One can throw either unchecked or checked exceptions using the throw keyword.  However, the throw keyword is mainly used to generate custom exceptions with the help of the throws keyword.

Syntax:

For example:

Java throw Keyword

Let’s try to understand the usage of the keyword throw with the help of some examples.

Throwing an Unchecked Exception

FileName: ThrowExample.java

Output:

Explanation: The try-catch block handles the explicitly raised exception in the divideByZero() method. Note that ArithmeticException is an example of an unchecked exception.

Throwing a Checked Exception

FileName: ThrowExample1.java

Output:

Explanation: Now, the throw keyword generates a checked exception that is being handled in the try-catch block. Note that the IOException is a checked exception.

Throwing a Custom Exception

The Java throw keyword can also be used to throw a custom exception. Custom exceptions play a very important role in Java projects. It is seen that most of the time, custom exceptions are used more frequently as compared to inbuilt exceptions. Custom exceptions come in very handy to show the project-specific messages. The following illustrates how one can raise a custom exception.

FileName: ThrowExample2.java

Output:

Explanation: Exception class must be used as a parent class to create our own exception. In order to show the desired messages, the constructor of the parent class, i.e., Exception class, must be invoked. The super(str); statement is doing the same. The rest of the code is straightforward to understand.

Pin It on Pinterest

Share This