有人可以向我解释为什么ArrayIndexOutOfBoundsException是运行时异常而不是编译时错误?在明显的情况下,当索引为负数或大于数组大小时,我不明白为什么它不能是编译时错误.
编辑:特别是在编译时已知数组的大小甚至索引,例如,int[] a = new int[10]; a[-1]=5;这应该是编译错误.
在下面的代码片段中,该printStackTrace()方法在catch block.中调用.运行程序后,您可以看到有时printStackTrace()连续几次运行而不是按printStackTrace()- > catch block- > 的顺序运行finally block.
如果您更改static boolean b为false然后按System.out.print(e)顺序执行.
那么为什么printStackTrace()表现方式不同呢?(带线程的东西??)
public class PrintStackTrace {
static boolean b = true;
public static void main(String[] args){
for(int i = 0; i < 100; i++){
try{
throw new Exception("[" + i + "]");
}
catch(Exception e){
if(b){
e.printStackTrace();
}
else{
System.out.print(e);
}
System.out.print(" Catch: " + i);
}
finally{
System.out.print(" Finally: " …Run Code Online (Sandbox Code Playgroud) 在下面的示例中,您可以看到无法使用外部catch子句捕获IOException(名为FOURTH)异常.这是为什么?我知道如果使用外部catch将其抛出到嵌套的try块中,则可以捕获异常.如果将b静态变量值更改为false,则可以看到这一点.
但是为什么我们不能使用外部catch来捕获嵌套catch子句中抛出的异常?
import java.io.*;
public class Exceptions {
static boolean b = true;
public static void main(String[] args){
try {
exceptions(b);
} catch (Exception e) {
System.out.println(e + " is handled by main().");
}
}
static void exceptions(boolean b) throws Exception{
try{
if(b) throw new FileNotFoundException("FIRST");
try{
throw new IOException("SECOND");
}
catch(FileNotFoundException e){
System.out.println("This will never been printed out.");
}
}
catch(FileNotFoundException e){
System.out.println(e + " is handled by exceptions().");
try{
throw new FileNotFoundException("THIRD");
}
catch(FileNotFoundException fe){
System.out.println(fe + " …Run Code Online (Sandbox Code Playgroud)