Professional Documents
Culture Documents
Handling
➢ try
➢ catch
➢ throw
➢ throws
➢ finally
try
{
Statement;
// generates exception or block of code
to monitor for error
}
catch(ExceptionTypeClass Object)
{
Statement; // process the exception
}
class Error3
{
public static void main (String args[ ])
{
int a =10;
int b =5;
int c = 5;
int x, y;
try {
x = a/ (b-c); // Exception here
}
catch(ArithmaticException e)
{
System.out.println (“Division by zero”);
}
y =a/ (b + c);
System.out.println (“y =” + y);
}
}
Output Division by zero
y=1
class NumFormExcp
{
public static void main(String args [ ])
{
String str1 = new String(“text12”);
int num1 = Integer.parseInt(str1);
// convert string to number
System.out.println(num1);
}
}
Syntax:
datatype methodname(parameter_list)throws exception-list
{
//body of method
}
class ThrowsException
{
public static void main(String args[ ]) throws
ArithmaticException
{
System.out.println(“inside main”);
int i=0;
int j=40/i;
System.out.println(“this statement is not printed”);
}
}
The output generated is as follows
inside main
Exception in thread “main”
java.lang.ArithmaticException: / by zero
at ThrowException.main(ThrowException.java:5)
➢ The finally clause is written with the try statement,
rather the try statement must have either the catch or
the finally block, and having both of them within the try
statement is also not a bar.
➢ The benefit of the finally block is that it is definitely
executed after a catch block or before the method quits.
This takes the form as:
try { try
// statements {
} // statement
catch (<exception> obj) }
{ finally
// statement {
} // statement
finally{ }
// statement
}
➢ That is why, while throwing the exceptions
you did not specifically include any package
for exception classes.
➢ Apart from the built-in exception classes
you can define your own exception classes.
➢ This is very useful when you want to define
exception types which are having a behavior
different from the standard exception types,
particularly when you want to do validations
in your application.
In this example the exception class is created and used
in the same java file, but it is possible to create and
store exception types in packages and use them globally.
import java.io.*;
import java.lang.Exception;
class MyException extends Exception
{
MyException(String Message)
{
super(Message);
}
}
class MyExceptionTest
{
public static void main (String args[ ])
{
BufferedReaderbr = new BufferedReader(new InputStreamReader(System.in));
try
{
System.out.println("Enter the number");
int no=Integer.parseInt(br.readLine());
if(no<0)
{
throw new MyException(“Number is negative");
}
else
{
throw new MyException(“Number is positive");
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
➢ Exception means abnormal condition.