Exceptions
Exceptions
• class Test {
public static void main (String[] args) {
int d=0;
int a=10/d;
} } Uncaught Exception.
• java.lang.ArithmeticException: / by zero.
class Test {
try {
int a=10/b;} scope of a is limited in try block.
class Test {
public static void main (String[] args) {
int a=10;
int b[] = new int [5];
try {
System.out.println(a/0);
System.out.println(b[5]);}
catch (ArithmeticException e){
System.out.println(“ Divide by zero Exception”);}
catch (ArrayIndexOutOfBoundsException e){
System.out.println(“ Array Index Exception”);}
}}
Nested try Statements
class Test {
public static void main (String[] args) {
int a=10;
int b[] = new int [5];
try{
try {
System.out.println(a/0);
System.out.println(b[5]);}
catch (ArithmeticException e) {
System.out.println(“Divide by zero
Exception”);}
}
catch (ArrayIndexOutOfBoundsException e){
System.out.println(“ Array Index Exception”);}
}}
Propagation of Exception
class Test {
public static void main (String[] args) {
class Test1 {
abc() {
System.out.println(10/0); }
}
try, catch and finally
class Test {
public static void main (String[] args) {
Test1 obj = new Test1();
System.out.println(obj.add());
}}
class Test1{
int add(){
try {
System.out.println(10/10);
return 1;}
catch (ArithmeticException e) {
System.out.println("Divide by zero Exception");
return 2;}
finally {
System.out.println("finally block");
return 3;}
}}
try and finally
class Test {
public static void main (String[] args) {
Test1 obj = new Test1();
System.out.println(obj.add());
}}
class Test1{
int add(){
try {
System.out.println(10/10);
return 1;}
finally {
System.out.println("finally block");
return 3;}
}}
Sequence of Catch Blocks
• Illegal Sequence
class Test {
public static void main (String[] args) {
int a[] = new int [5];
try {
System.out.println("abc".substring(3,2));
System.out.println(a[5]);
General Class cannot
}
comes before Special
classes.
catch (IndexOutOfBoundsException e) {
System.out.println(“ Index Exception");}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println(“ Array Index Exception");}
catch (StringIndexOutOfBoundsException e) {
System.out.println(“ String Index Exception");}
finally {
System.out.println(“ finally block ");}
}}