Login    New User    Forgot Password    Help      

Try Catch

Java Tutorials

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. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following:

syntax

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

Example

// Program that accepts no by argument and divide itself by its one no less than itself
// Arithmetic exception handler
// Try and catch

class ex
{
int m;
        void div(int n)
        {
        // monitor block of code
        try
                {
                n--;
                m=m/n;
                // this will not print on the time of divide by o
                System.out.println("Divide  "+ ++n +" by " + --n +" == " + m);
                }
        catch (ArithmeticException e)
                {
                System.out.println("Not possible");
 & nbsp;              // use following statement to see the error
                //System.out.println(e);
                }
       
       }
}
 class  ex1
{
public static void main(String args[])
{
int n;

n=Integer.parseInt(args[0]);
ex ob1=new ex();
ob1.div(n);

}
}

 

Output

Java Tutorials