Try Catch In Java Exception Handling


Try block

The try block contains a sequence of statements that can throw an exception. The try block is always followed by a catch block that handles exceptions thrown by the corresponding try block. The try block must be followed by a catch block or finally block or both.

Syntax of try block:

try{ //statements that may cause an exception }

Catch block

The catch block is where you handle exceptions, which must follow the try block. A single try block can have several link capture blocks. You can catch different types of exceptions in different catch blocks. When an exception occurs in the try block, the corresponding catch block that handles that particular exception is executed. For example, if an arithmetic exception occurs in the try block, the statements contained in the catch block for the arithmetic exception will be executed.

Syntax of try catch in java:

try { //statements that may cause an exception } catch (exception(type) e(object)) { //error handling code }


Write a java program to read 2 integers a and b. Compute a/b and print ,when b is not zero. Raise an exception when b is equal to zero.

import java.util.Scanner; public class Division { public static void main(String arg[]){ int a ,b ,quotient; // scanner gets its input from the console. Scanner s = new Scanner(; // Get the numerator and denominator System.out.println("Enter Numerator:"); a=s.nextInt(); System.out.println("Enter Denominator:"); b=s.nextInt(); try { quotient =a/b; System.out.println("Quotient="+quotient); } catch (ArithmeticException ae){ System.out.println(ae); } } }


Enter Numerator:21
Enter Denominator:7

Enter Numerator:5
Enter Denominator:0
java.lang.ArithmeticException : / by zero


Clear Any Java Interview by Reading our Ebook Once.

Can you clear Java Interview?

Looking for Vacation Hotels? Check Below:-


Have Technical Questions????

Hot Deals ends in

Technical Quiz You might be Interested in:
Relax Zone:
Play 2048 Online
Play 2048 Game Online

Search Tags

    Simple Example to Understand Try Catch in Java

    Understand Try Catch Block in Java

    Java Try Catch Block Exception Handling