Try Catch In Java: In our previous post, we have learned about what is an exception, types of exception and in this post, we are going to learn about how we can handle by using Try Catch and finally in Java programming language.
Try Catch Java
Java provides some specific keyword for handling the Exceptions one by one and also try to understand them with some simple Java programs:
Try Block In Java
By using this keyword we can create a block where we write those statements which may generate some exceptions. a try block is always written with catch block or finally block which handles the exception which occurs during the execution of the program, the syntax of try block looks like below
try { //statements that may cause an exception }
Catch block In Java
In Java Catch block is used to handle the exception and it always must follow a try block. in a program a single try block can have multiple catch block which is used to handle different exceptions in the different catch block. so that when a particular exception occurs that time a particular catch block will be executed. The syntax for catch block looks like below
try { //statements that may cause an exception } catch (exception(type) e(object)) { //error handling code }
Finally Block In Java
Finally block is an optional block that can be used with the try-catch block in java. during the execution of the program if an exception occurs when the flow of the program is interrupted because of that some resources will leave as in open state and not get closed. in that scenario finally, block helps us to close such types of scenarios because finally block is executed always whether an exception occurs or not. and the syntax looks like below
try { //statements that may cause an exception } catch (exception(type) e(object)) { //error handling code } finally { //statements to release the resources }
How to Handle Exception Using Try Catch Block In Java Example Program?
package com.softwaretestingblog.programs; public class UsingTryCatch { public static void main(String[] args) { // TODO Auto-generated method stub try { int i=9; int z=i/0; System.out.println("The Value Of I Is -" +z); } catch(ArithmeticException e) { System.out.println(e.getMessage()); //e.printStackTrace(); } } }
Output:
/ by zero
Ref: article
Leave a Reply