Try Catch Block in Java

by | Dec 20, 2020 | Java

Home » Java » Try Catch Block in Java

Try Block

The Java Try-Catch Block is used to handle exceptions. The Try block is separate from the Catch block but these are used together one after the other. The code that you want to check for exceptions or you know might throw an exception is kept inside the try block. Once an exception is caught, the rest of the try block is not executed and the program flow goes to the catch block. It is therefore recommended not to keep the entire code inside a try block but only the required part that might throw an exception. A try is followed by a catch block and/or the finally block.

Catch Block

The Catch Block is where any exception thrown in the Try block is handled. This is done by specifying the type of exception in the block parameter. The type of exception declared should be the parent exception or the type of exception that will be generated from the code in the try block. Normally, the generated exception is mentioned and considered a programming convention. The Catch block comes just after the try block and before the finally block. More than one catch block can be used to catch several types of exceptions.

Example

Let us discuss an example where we run a simple program with and without a try-catch block. We will try to divide 50/0 which will give an arithmetic exception.

public class DemoTryCatch
{
public static void main (String args [])
{
int ans = 50/0;
System.out.println (“Hello World”);
}
}

OUTPUT

Exception in thread “main” java.lang.ArithmeticException: / by zero

Using Try Catch block

public class Demo2
{
public static void main (String args [])
{
try
{
int ans = 50/0;
}
catch (ArithmeticException e)
{
System.out.println(e);
}
System.out.println(“Hello World”)
}
}

OUTPUT

java.lang.ArithmeticException: / by zero
Hello World

Author

0 Comments

Submit a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author