Catching Exceptions in Java Programming

Catching Exceptions in Java Programming

Previous Home Next

 

To catch an exception in Java, you write a try block with one or more catch clauses. Each catch clause specifies one exception type that it is prepared to handle.
Catch {}block is used to catch the exception.

During the program execution if any error occurs and you want to print your own message or the system message about the error then you write the part of the program which generate the error in the try{} block and catch the errors using catch() block.
 


 
public class ExceptionHandling
{
public static void main(String[] args) throws Exception{
try{
int x,y;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
x = Integer.parseInt(in.readLine());
y = Integer.parseInt(in.readLine());
}
catch(NumberFormatException ex){
System.out.println(ex.getMessage() + " is not a numeric value.");
System.exit(0);
}
}


Previous Home Next