小编Laz*_*don的帖子

为什么ArrayIndexOutOfBoundsException不是编译时错误?

有人可以向我解释为什么ArrayIndexOutOfBoundsException是运行时异常而不是编译时错误?在明显的情况下,当索引为负数或大于数组大小时,我不明白为什么它不能是编译时错误.

编辑:特别是在编译时已知数组的大小甚至索引,例如,int[] a = new int[10]; a[-1]=5;这应该是编译错误.

java compilation compile-time indexoutofboundsexception

11
推荐指数
2
解决办法
4433
查看次数

为什么printStackTrace()和其他方法之间的执行顺序似乎是不确定的?

在下面的代码片段中,该printStackTrace()方法在catch block.中调用.运行程序后,您可以看到有时printStackTrace()连续几次运行而不是按printStackTrace()- > catch block- > 的顺序运行finally block.

如果您更改static boolean bfalse然后按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)

java printstacktrace

3
推荐指数
1
解决办法
742
查看次数

为什么我不能使用'outer'catch来捕获嵌套catch子句中抛出的异常?

在下面的示例中,您可以看到无法使用外部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)

java nested exception try-catch

0
推荐指数
1
解决办法
2406
查看次数