Java Tutorial/Statement Control/try catch
Содержание
An example of nested try statements.
class NestTry {
public static void main(String args[]) {
try {
int a = args.length;
int b = 42 / a;
System.out.println("a = " + a);
try {
if (a == 1)
a = a / (a - a); // division by zero
if (a == 2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
} catch (ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}
Catch different Exception types
class MyException extends Exception {
MyException() {
super("My Exception");
}
}
class YourException extends Exception {
YourException() {
super("Your Exception");
}
}
class LostException {
public static void main(String[] args) {
try {
someMethod1();
} catch (MyException e) {
System.out.println(e.getMessage());
} catch (YourException e) {
System.out.println(e.getMessage());
}
}
static void someMethod1() throws MyException, YourException {
try {
someMethod2();
} finally {
throw new MyException();
}
}
static void someMethod2() throws YourException {
throw new YourException();
}
}
catch divide-by-zero error
public class MainClass {
public static void main(String args[]) {
int d, a;
try {
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { //
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
Demonstrate multiple catch statements.
class MultiCatch {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
} catch (ArithmeticException e) {
System.out.println("Divide by 0: " + e);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
Handle an exception and move on.
import java.util.Random;
public class MainClass {
public static void main(String args[]) {
int a = 0, b = 0, c = 0;
Random r = new Random();
for (int i = 0; i < 32000; i++) {
try {
b = r.nextInt();
c = r.nextInt();
a = 12345 / (b / c);
} catch (ArithmeticException e) {
System.out.println("Division by zero.");
a = 0; // set a to zero and continue
}
System.out.println("a: " + a);
}
}
}
Try statements can be implicitly nested via calls to methods
class MethNestTry {
static void nesttry(int a) {
try {
if (a == 1)
a = a / (a - a);
if (a == 2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
}
public static void main(String args[]) {
try {
int a = args.length;
int b = 42 / a;
System.out.println("a = " + a);
nesttry(a);
} catch (ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}