Introduction
The code which is expected to generate the exception must be enclosed in the try and catch block. The very basic form of the exception-handling block is as following:
Code: Java
try
{
//code which is expected to generate the exception
}
catch (<ExceptionTypeClass> object)
{
//statements to handle the exception
}
Consider the following program, which demonstrates how the runtime environment handles an exception when it is generated. It is further modified to handle the exception through the code itself. The exception raised is the NumberFormatException. It arises when you try to convert a string to number format, and the string is either empty or does not contain the number in a proper format.
Code: Java
class NumFormExcp
{
public static void main(String args[ ])
{
String str1 = new String("abc123");
int num1 = Integer.parseInt(str1); //converts string to number
System.out.println (num1);
}
}
Code:
Exception in thread "main" java.lang.NumberFormatException: For input string: "abc123" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at NumFormExcp.main(NumFormExcp.java:7)
The program given below shows, how you can handle this exception:
Code: Java
class NumFormExcp
{
public static void main (String args [ ])
{
try
{
String str1 = new String ("abc123");
int num1 = Integer.parseInt (str1);
System.out.println (num1);
}
catch (NumberFormatException e)
{
System.out.println ("##Wrong Number##");
}
}
}
##Wrong Number##
In the listing the NumberformatException is not left unhandled and there is a catch block ready to catch it. Once the exception is caught the statements inside the catch block execute, giving the appropriate message.
How to throw Exceptions in Java? >>