Catching Exceptions in JAVA

 Catching Exceptions:


The try-catch Statements


class DivByZero {
public static void main(String args[]) {
try {
System.out.println(3/0);
System.out.println(“Please print me.”);
} catch (ArithmeticException exc) {
//Division by zero is an ArithmeticException
System.out.println(exc);
}
System.out.println(“After exception.”);
}
}


Multiple catch

class MultipleCatch {
public static void main(String args[]) {
try {
int den = Integer.parseInt(args[0]);
System.out.println(3/den);
} catch (ArithmeticException exc) {
System.out.println(“Divisor was 0.”);
} catch (ArrayIndexOutOfBoundsException exc2) {
System.out.println(“Missing argument.”);
}
System.out.println(“After exception.”);
}
}

Nested try's


class NestedTryDemo {
public static void main(String args[]){
try {
int a = Integer.parseInt(args[0]);
try {
int b = Integer.parseInt(args[1]);
System.out.println(a/b);
} catch (ArithmeticException e) {
System.out.println(“Div by zero error!");
} } catch (ArrayIndexOutOfBoundsException) {
System.out.println(“Need 2 parameters!");
} } }


Nested try's with methods

class NestedTryDemo2 {
static void nestedTry(String args[]) {
try {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
System.out.println(a/b);
} catch (ArithmeticException e) {
System.out.println("Div by zero error!");
} }
public static void main(String args[]){
try {
nestedTry(args);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Need 2 parameters!");
} } }


Post a Comment (0)
Previous Post Next Post