Managing Errors and Exceptions
Managing Errors and Exceptions
and Exceptions
What You Will Learn
Use to
try, watch for
throw, indicate exceptions
handle
catch
2
Syntax Errors, Runtime Errors, and
Logic Errors
class Error1
{
public static void main(String args[])
{
System.out.println(“Hello Java”)
}
}
Statement that
causes Exception
Catch Block
Statement that
handles the Exception
What is Try Block?
The try block contains a block of
program statements within which an
exception might occur.
A try block must followed by a Catch
block or Finally block or both.
System.out.println(“Division by zero”);
}
int y=a/(b+c);
System.out.println(“Y= “ +y)
}
}
public static void main(String args[])
{
int num1, num2;
try { num1 = 0;
Error: Don't divide a number by zero
num2 = 62 / num1;
I'm out of try-catch block in Java.
System.out.println("Try block
message");
}
catch (ArithmeticException e)
{
System.out.println("Error: Don't divide a number by
zero");
}
System.out.println("I'm out of try-catch block in
Java.");
}
Multiple catch Statements
try {
//Protected code
}
catch(ExceptionType1 e1) {
//Catch block
}
catch(ExceptionType2 e2) {
//Catch block
}
catch(ExceptionType3 e3) {
//Catch block
}
Sequence of Events
Preceding step
try block
statement
unmatched catch
matching catch
unmatched catch
next step
class Example2{
public static void main(String args[]){
try{
int a[]=new int[7];
a[4]=30/0;
System.out.println("First print statement in try
block"); }
catch(ArithmeticException e){
System.out.println("Warning: ArithmeticException"); }
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Warning:ArrayIndexOutOfBoundsExcepti
on"); }
catch(Exception e){
System.out.println("Warning: Some Other exception");
}
System.out.println("Out of try-catch block...");
Multiple catch Statements
A try block can have any number of catch
blocks.
A catch block that is written for catching the
class Exception can catch all other
Syntax:
exceptions.
catch(Exception e)
{
//This catch block catches all the exceptions
}
try block
statement
unmatched catch
matching catch
unmatched catch
finally
next step