Beginners Programs :

Java Exception Throw Clause – Tutorial & Examples

Java exception Throw Clause – “throw” clause is used to throw an exception from our side. Normally, the system throws an exception when a runtime error occurs. Generally “throw” is used in two situations

  1. When we want to throw a new exception object (that is created by us)
  2. When we want to pass an exception object from one place to another place (created by us or the system)

In most of the situations when a problem occurs the system will throw the exception, in that case, we need not use “throw”. But when we want to throw an exception, “throw” is required.

The Background Of Throw Clause Exception

When a situation comes up for we to generate an exception, we create an object corresponding to the situation and store the information about the error in that object. Here, we are free to create the exception object. It means we can create an object of

  • ArithmeticException
  • NumberFormatException
  • ArrayIndexOutOfBoundsException or any other class

We just should be judicious in selecting the class. If we feel none of the existing classes suits our requirements then we can create our own exception class.

Once such an object is created, we should throw that object to the catch block. If there is no catch block to receive the object, then the program will be terminated.

Otherwise, the object will be received by the catch block and the code we have written in the catch block will be executed. If we have used an Exception reference at catch block, it can be handled as Exception is the parent class for almost all the exceptions in Java.

“throw” a fresh exception

By default, the system throws an Exception when something goes wrong.

  • It means the system creates an object and throws it to catch block.
  • There may be some situation that it is acceptable to the system but not acceptable to the requirements of our program.

In that case, we create and throw the exception objects. Creating an exception object is similar to creating a normal object. To throw the created object, we use the keyword ‘throw’. This can be seen in the following example.

Example:

We can create our own exceptions. Every exception class that we create should be part of the exception hierarchy. So we should make our class a child class of any existing exception classes.

Example:

Passing an exception using “throw”

If we come to a catch block from a try block and wanted to pass that exception to another catch block then we can use “throw” as shown in the following example.

In this case, the throwing block (catch) should be part of an outer try-catch mechanism and the throwing catch block should be inside the outer try block.

In this example, if we execute the program without any command line arguments, then the output will be “ABCE”. With one argument (or two arguments), the output will be “ABCD”. With three or more arguments the output will be “A”.