hrowable类定义了3个异常处理方法

public string getllessage() :获取异常的描述信息,原因(提示给用户的时候,就提示错误原因。

public string tostring():获取异常的类型和异常描述信息(不用)。

public void printStackTrace():打印异常的跟踪栈信息并输出到控制台。

多个异常使用捕获又该如何处理呢?

1.多个异常分别处理。

2.多个异常一次捕获,多次处理。

3.多个异常一次捕获一次处理。

Throwable的使用场景:

对于Throwable类的场景,实际项目当中比较少,更多的是其子类以及派生的子类,主要分为Error、Exception两大派,用于区分项目当中发生的详细异常信息

举例:

Strng getMessage()返回此throwable的简短描述

String toString()返回此throwable迭代纤细消息字符串。

void printStackTrace();JVM打印的异常对象,默认此方法,打印的异常信息是最全面的

 

 

 

 

 

 

案例:

 

 

 

 

finally代码块:

finally:有一些特定的代码无论异常是否发生,都需要执行。另外,因为异常会引发程序跳转,导致有些语句执行不到。而finally就是解决这个问题的,在finally代码块中存放的代码都是一定会被执行的。

.finalLy不能单独使用,必须和try一起使用.

finally—般用于资源释放(资源回收)

finally的语法:

try...catch....finally:自身需要处理异常,最终还得关闭资源。

举例:

 

 

 举例:

public static void main(String[] args) {
  int result = ll();
  System.out.println(result);// 10001
}
public static int ll() {
  int temp = 10000;
  try {
    throw new Exception();
  } catch (Exception e) {
    return ++temp;
  } finally {
    temp = 99990;
  }
}

举例:

public static void main(String[] args) { 
        try { 
            BufferedReader br = new BufferedReader(new FileReader("file.txt"));
            System.out.println(br.readLine()); 
            br.close(); 
        } catch (IOException e) { 
           System.exit(2); 
        } finally { 
            System.out.println("Exiting the program"); 
        } 
    } 

举例:

public static void main(String[] args) { 
        // 修改 SecurityManager 
        System.setSecurityManager(new SecurityManager() { 
            @Override 
            public void checkExit(int status) { 
                throw new SecurityException("不允许退出"); 
            } 
        }); 
        try { 
            BufferedReader br = new BufferedReader(new FileReader("file.txt"));
            System.out.println(br.readLine()); 
            br.close(); 
        } catch (IOException e) { 
            System.exit(2); 
        } finally { 
            System.out.println("Exiting the program"); 
        } 
    }

 

 

 
 
posted on 2022-07-07 17:11  淤泥不染  阅读(77)  评论(0编辑  收藏  举报