follow

Thursday, 8 August 2013

Use of "try catch"" for handling the Exception block :JAVA Programming by "Gopal Krishna"

Catching Exceptions:


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:

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

}


1.

public class ex1
{
public static void main(String arg[])
{
String s1="abc";
try
{
int a =Integer.parseInt(s1);
System.out.println(a);
}
catch(Exception e)
{
System.out.println(e);
}
}

}


2.

public class ab
{
public static void main(String arg[])
{
try
{
int a=Integer.parseInt(arg[0]);
}
catch(Exception e)
{
System.out.println("no invalid");
}
System.out.println("no valid");
}
}

Multiple catch Blocks:

A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following:

try
{
   //Protected code
}catch(ExceptionType1 e1)
{
   //Catch block
}catch(ExceptionType2 e2)
{
   //Catch block
}catch(ExceptionType3 e3)
{
   //Catch block
}


No comments:

Post a Comment