Try, catch, throw and throws in Java

JavaObject Oriented ProgrammingProgramming

Try and catch in Java

A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception.

Following is the syntax for try and catch −

try {
   // Protected code
} catch (ExceptionName e1) {
   // Catch block

A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.


Let us now see an example to implement try and catch −

 Live Demo

public class Demo {
   public static void main(String args[]) {
      try {
         int a[] = new int[5];
         System.out.println("Access element eighth :" + a[7]);
      } catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("Exception thrown :" + e);
      System.out.println("Out of the block");


Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 7
Out of the block

throw and throws in Java

If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature.

You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword.

The throws is used to postpone the handling of a checked exception and throw is used to invoke an exception explicitly.

Published on 26-Sep-2019 12:46:01