throw keyword Create User defined Exceptions

throw keyword Create User defined Exceptions

Java permits the creation of user defined exceptions as per the needs of coding. To use it Developer uses throw keyword. Explained in simple terms, examples and screenshots to Beginner in this tutorial "throw keyword User defined Exception".

Using throw Keyword

To display a message, a number of ways exist in Java (in C, it is printf() only). Observe the following program, a simple and usual way to display the message "no money please".

The above message can be displayed using an exception class also as follows.

throw keyword User defined Exception
Output screen on throw keyword User defined Exception

ArithmeticException e = new ArithmeticException("No money please");
throw e;

In the if block, an object of ArithmeticException is created and the message is passed to the constructor. With throw keyword the exception object is thrown to the system. So far, in the previous programs, system is throwing the exceptions and we are handling them. But instead, the programmer can throw the exceptions to the system and system handles. throw is used by the programmer to throw the exception to the system. System simply takes the exception object, displays the message and terminates the program (as we are not handling).

Creating User defined Exceptions (throw keyword User defined Exception)

Java permits to create our own exceptions and use in the program. What is the necessity to create our own exceptions when Java API comes with hundreds of exception classes? Sometimes in programming, as in the previous program, the problem and the exception used may not have good relation and meaning. An exception class clearly denotes what for it is meant. For example, ArithmeticException informs the problem of some arithmetic operation failure and NumberFormatException informs the data input given cannot be formatted into a number. But in the previous program, the bank balance is no way connected with ArithmeticException class. To have good meaning, we can create our own exception. If an exception like NoBalanceException exists, it well suits for the problem of insufficient funds. Following program illustrates.

Example on throw keyword User defined Exception

throw keyword User defined Exception
Output screenshot on throw keyword User defined Exception

The previous program is modified to suit the user-defined exception. To reflect the problem and as every exception is a class, a class is created by name, NoBalanceException. To exploit the reusability of Java, the Exception class is extended. The designers clearly defined the control flow of exception handling in Exception class. We are using this by extending Exception class. The NoBalanceException constructor calls the super class Exception constructor and passes the problem with super().

In the main() method of YesBank, we have created an object of NoBalanceException and passed the message "No balance please". This message reaches the Exception class constructor via NoBalanceException class. The Exception class knows very well what to do with the problem message. It displays the message and terminates the program (as we are not handling it). The NoBalanceException object, e, is thrown to the system. System receives the object, displays the message and terminates the program.

NoBalanceException e = new NoBalanceException("No balance please");
throw e;

The above two statements can be simplified by using anonymous object as follows.

throw new NoBalanceException("No balance please");

Everything is right, then what is the necessity to throw the exception in the main() method declaration? It is a must else the program does not compile. It is so because we extended a checked exception called Exception. If an unchecked exception is extended like ArithmeticException, then the throws clause can be removed from main() declaration.

Handling exceptions – Three styles

Altogether, there are three styles of handling the exceptions.

  1. Using try-catch block; the robust way
  2. Using throws in place of try-catch, not a robust way
  3. To throw the exception object to the system using throw keyword, not a robust way

Differences between throw and throws keywords

Even though they look alike and used with exception handling mechanism only, they differ a lot in their meaning and usage.

a) throws keyword

"throws" can be utilized by the programmer in two ways.

  1. It is used by the designer of a method to claim the exception. Claiming is nothing but informing the programmer about the potential problems that may arise while using the method.
  2. The other way is to use as an alternative to try-catch block which is not a robust way.

b) throw keyword

"throw" is used by the programmer to throw an exception object explicitly to the system. Mostly used with user-defined exceptions.

Printing exception message – getMessage() and printStackTrace()

An exception message can be printed in three ways. The first way is printing the exception object thrown by the JVM. The other two are using the methods of Throwable class – getMessage() and printStackTrace().

1. Printing exception object

Following is the screenshot for the above catch block.

2. Using getMessage()

The getMessage() method prints the following way.

3. Using printStackTrace()

The printStackTrace () method prints the following way.

The above three screenshots can infer you the following information.

  1. System.out.println(e) prints the exception class name (java.lang.ArithmeticException) and also the exception message ( / by zero).
  2. System.out.println(e.getMessage()) prints exception message ( / by zero) only indicating the cause of exception.
  3. e.printStackTrace() prints the exception class name with the message particulars and also the line number where the problem arises (traces the actual problem).

Some more discussion is available on printing exceptions messages in Java Exception Messages.

13 thoughts on “throw keyword Create User defined Exceptions

  1. Srinivas p

    hi sir Good afternoon..can we use throw keyword for handling pre-defined exeptions..? if yes then please explain with simple program..and why we are using this throw keyword with in the method only,what will happen if we are using outside the method..please reply me..Thank you.

  2. pavan

    Hi sir first of all tq very much for this valuable notes i have a doubt please clear me

    class NoBalanceException extends Exception {
    public NoBalanceException(String problem) {

    public class YesBank {
    public static void main(String args[]) throws NoBalanceException {
    int balance = 100, withdraw = 1000;
    if (balance < withdraw) {
    NoBalanceException e = new NoBalanceException("No balance please");
    throw e;
    } else {
    System.out.println("Draw & enjoy, Best wishes of the day");

    in this program we are calling 'Exception' class constructor with 'NoBalanceException' class constructor but we have not created any object for 'Exception' class and we are not calling 'Exception' class constructor then this message is passed to 'Exception' class the message is printing. please clear me sir

    1. S. Nageswara Rao, Corporate Trainer

      If you see throws keyword in any method definition, think it is checked exception. Many predefined methods of Java (known as Java API) throws exceptions. See this:

      public int read() throws IOException

      read() is a predefined method of InputStream class. Now, IOException is a checked exception.

Leave a Reply

Your email address will not be published. Required fields are marked *