Java Throws

Java Throws keyword

Java Throws

If you don’t want to handle the exception and let the others handle it. You can do it simply by declaring what exception may occur at run time using throws keyword.

In this tutorial, we will discuss about throws keyword and how to declare an exception in java programming.

Java Throws keyword


Throws Keyword


Throws keyword allows you to declare an exception which may occurs while perform an action. Throws keyword can only be used with the methods. When that methods is used, it may throw an exception at run time as declared by throws keyword. It is now programmers responsibility how to handle that exception in program.

When we define a method, we can also declare the exception which may occur when it is used. So that it can be handled properly by the programmer itself. 

We can only throw checked exception because it is programmers responsibility to handle the exception before it can be used.

Basic syntax

return_type methodName() throws ExceptionClass, AnotherExcpeiotnClass {
  // Method Code.
}

An example on Throws keyword

class ThrowsExample {

  public static void exceptionDemo() throws Exception {
       throw new Exception("Exception has been thrown.");
  }

  public static void main(String arg[]) {

       try {
            exceptionDemo();
       } catch (Exception e) {
          System.out.println("Exception : " + e.getMessage());
       }
  }
}

Output:
Exception : Exception has been thrown.

Note in the above example, if you don’t enclose the method exceptionDemo() with try catch block, you code will not compile. Because method is throwing an exception, so it must be handled by the programmer during programming.

Related Post

Leave a Reply

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