In: Computer Science
Provide a description of the try .. catch statement. As part of your description you must describe how this statement can be used to handle errors and exceptions and include an example of try ... catch implemented to handle an error or exception within a Java program.
Please Don't copy from someone else.
"Try Catch block is used to handle any exceptions smoothly. "
I will explain this concept in a simple and understandable way for you.
Let's write a program that divides a number.
SEE THE EXAMPLE:
import java.util.Scanner; public class ExceptionDemo { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); // read a number here System.out.print("Enter a number: "); // Take the number into 'num' variable int num=scanner.nextInt(); int divisionAnswer=10/num; System.out.println("The Answer is: "+divisionAnswer); System.out.println("Program has completed..!!"); } }
If we enter ZERO (0), we will get an exception and the program terminates abnormally.
====================
If we don't use any exception handling techniques, we will get exceptions and errors and our program will terminate abnormally.
====================
USE TRY-CATCH BLOCK for handling such type of exceptions.
import java.util.Scanner; public class ExceptionDemo { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); // read a number here System.out.print("Enter a number: "); // Take the number into 'num' variable int num=scanner.nextInt(); // This Code may raise an error. // So, keep it in try block try { // perform a simple division // If we divide a number by ZERO, we will get an Exception int divisionAnswer=10/num; System.out.println("The Answer is: "+divisionAnswer); } catch(ArithmeticException e) { // If there is any exception, the control comes here. System.out.println("Division By ZERO Exception. Can't divide a number by Zero."); } System.out.println("Program has completed..!!"); } }
====================================
OUTPUT: