在这里,我们将分析一些异常处理代码,以更好地理解这些概念。
尝试在以下代码中查找错误(如果有)
代码1:
public class prog {
    public static void main(String arg[]) {
        try {
            int a = 10, b = 0;
            int c = a / b;
        } catch (RuntimeException e) {
            System.out.println(e.getMessage());
        } catch (ArithmeticException e) {
            System.out.println(e.getMessage());
        }
    }
}输出结果
/prog.java:8: error: exception ArithmeticException has already been caught
        } catch (ArithmeticException e) {
          ^
1 error说明:
当使用多个catch块时,我们必须确保以与异常继承相反的顺序捕获异常。这意味着必须在最一般的例外之前捕获最特定的例外。必须在RuntimeException之前捕获ArithmeticException。
代码2:
public class prog {
    public static void main(String arg[]) {
        try {
            throw new Integer(25);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}输出结果
/prog.java:4: error: incompatible types: Integer cannot be converted to Throwable throw new Integer(25); ^ Note: /prog.java uses or overrides a deprecated API. Note: Recompile with -Xlint:deprecation for details. 1 error
说明:
我们只能抛出Throwable类或继承该类的类的对象。Integer类不会扩展Throwable类,因此,我们不能抛出Integer类的对象。类似地,“ throw 25”的陈述是错误的。不像C ++,我们可以抛出对象,而在Java中,我们只能抛出那些继承Throwable类的对象。
代码3:
public class prog {
    public static void main(String arg[]) {
        err ob1 = new err();
        ob1.func();
    }
}
class err {
    void func() {
        try {
            System.out.println("Inside try");
        } finally {
            System.out.println("Inside finally");
        }
    }
}输出结果
Inside try Inside finally
说明:
不必将catch块附加到try块。try语句可以直接与finally语句关联。
代码4:
import java.io.*;
public class prog {
    public static void main(String arg[]) {
        err ob1 = new err();
        ob1.func();
    }
}
class err {
    void func() throws IOException {
        try {
            System.out.println("Inside try");
        } catch (Exception e) {
            System.out.println("Inside catch");
        } finally {
            System.out.println("Inside finally");
        }
    }
}输出结果
/prog.java:6: error: unreported exception IOException; must be caught or declared to be thrown ob1.func(); ^ 1 error
说明:
如果说一个函数抛出任何检查的异常,则调用者必须捕获该检查的异常。语句“ void func()throws IOException ”清楚地表明,该函数可以抛出必须由调用方处理的IOException。可以通过在try-catch块中包含' ob1.func() '语句来纠正该错误。
代码5:
import java.io.*;
public class prog {
    public static void main(String arg[]) {
        err ob1 = new err();
        ob1.func();
    }
}
class err {
    void func() throws RuntimeException {
        try {
            System.out.println("Inside try");
            try {
                int[] a = new int[10];
                int c = 10;
                a[c] = 0;
            }
        } catch (Exception e) {
            System.out.println("Inside catch");
        }
    }
}输出结果
/prog.java:14: error: 'try' without 'catch', 'finally' or resource declarations
            try {
            ^
1 error说明:
每个try块必须具有关联的catch或finally块。在代码中,内部try块没有关联的catch或finally块。