Exception Objects
• An exception is an abnormal condition that
arises in a code sequence at rum time.
• Exception is a way of signaling serious problem.
• An Exception in Java is an Object that’s created
when an abnormal situation arises in your
program.
• The Exception Object has data members that
store information about the nature of the problem.
Exception Handling
• class Test {
public static void main (String[] args) {
int d=0;
int a=10/d;
} } Uncaught Exception.
• [Link]: / by zero.
• This Exception is caught by java default handler.
Catching Exception
• It allow you to fix the errors.
• It prevents the program from automatically
terminating.
try and catch Blocks
• Use try block to identify the code that can throw
exceptions.
• Use catch blocks to catch the exceptions.
try and catch Block
• Code generates ArithmeticException.
class Test {
public static void main (String[] args) {
int b=0;
try {
int a=10/b;} scope of a is limited in try block.
catch (ArithmeticException e){
[Link](“ Divide by zero Exception”);}
}
}
try and catch Blocks
• Code generates ArithmeticException and
ArrayIndexOutOfBoundsException.
class Test {
public static void main (String[] args) {
int a=10;
int b[] = new int [5];
try {
[Link](a/0);
[Link](b[5]);}
catch (ArithmeticException e){
[Link](“ Divide by zero Exception”);}
catch (ArrayIndexOutOfBoundsException e){
[Link](“ Array Index Exception”);}
}}
Nested try Statements
class Test {
public static void main (String[] args) {
int a=10;
int b[] = new int [5];
try{
try {
[Link](a/0);
[Link](b[5]);}
catch (ArithmeticException e) {
[Link](“Divide by zero
Exception”);}
}
catch (ArrayIndexOutOfBoundsException e){
[Link](“ Array Index Exception”);}
}}
Propagation of Exception
class Test {
public static void main (String[] args) {
Test1 obj1 = new Test1();
try{
[Link]();}
catch (ArithmeticException e){
[Link](“Divide by zero Exception”);}
}}
class Test1 {
abc() {
[Link](10/0); }
}
try, catch and finally
class Test {
public static void main (String[] args) {
Test1 obj = new Test1();
[Link]([Link]());
}}
class Test1{
int add(){
try {
[Link](10/10);
return 1;}
catch (ArithmeticException e) {
[Link]("Divide by zero Exception");
return 2;}
finally {
[Link]("finally block");
return 3;}
}}
try and finally
class Test {
public static void main (String[] args) {
Test1 obj = new Test1();
[Link]([Link]());
}}
class Test1{
int add(){
try {
[Link](10/10);
return 1;}
finally {
[Link]("finally block");
return 3;}
}}
Sequence of Catch Blocks
• Illegal Sequence
class Test {
public static void main (String[] args) {
int a[] = new int [5];
try {
[Link]("abc".substring(3,2));
[Link](a[5]);
General Class cannot
}
comes before Special
classes.
catch (IndexOutOfBoundsException e) {
[Link](“ Index Exception");}
catch (ArrayIndexOutOfBoundsException e) {
[Link](“ Array Index Exception");}
catch (StringIndexOutOfBoundsException e) {
[Link](“ String Index Exception");}
finally {
[Link](“ finally block ");}
}}