在出现程序错误时,异常有两种抛出方法,一种是直接抛出,另一种是封装再抛出。根据抛出的方式不同,我们有着对应的解决方法。同时,我们也可以主要采取捕捉的方法去搜集这些异常的情况,然后进行批量的处理。下面就异常抛出的两种类型和异常捕捉的处理带来介绍。
1.异常抛出
(1)直接抛出
通常应该捕获那些知道如何处理的异常,将不知道如何处理的异常继续传递下去。传递异常可以在方法签名处使用 throws 关键字声明可能会抛出的异常。
private static void readFile(String filePath) throws IOException {
File file = new File(filePath);
String result;
BufferedReader reader = new BufferedReader(new FileReader(file));
while((result = reader.readLine())!=null) {
System.out.println(result);
}
reader.close();}(2)封装再抛出
有时我们会从 catch 中抛出一个异常,目的是为了改变异常的类型。多用于在多系统集成时,当某个子系统故障,异常类型可能有多种,可以用统一的异常类型向外暴露,不需暴露太多内部异常细节。
private static void readFile(String filePath) throws MyException {
try {
// code
} catch (IOException e) {
MyException ex = new MyException("read file failed.");
ex.initCause(e);
throw ex;
}}2.捕获多种异常
public static void main(String[] args) {
try {
process1();
process2();
process3();
} catch (IOException | NumberFormatException e) { // IOException或NumberFormatException
System.out.println("Bad input");
} catch (Exception e) {
System.out.println("Unknown error");
}
}以上就是关于java异常的解决方法,需要我们明确异常抛出的不同方式,以及主动捕捉多种异常的方法,当异常发生时,这些方法都能有效的处理。



