面试题答案
一键面试运行时异常(RuntimeException及其子类)
- 方法声明:
- 方法在声明时不需要显式声明抛出运行时异常。例如:
public void someMethod() { // 可能会抛出运行时异常,如空指针异常 String s = null; s.length(); }
- 调用处:
- 调用一个可能抛出运行时异常的方法时,调用者可以选择捕获处理异常,也可以不处理,让异常向上层调用栈传播。例如:
public class Main { public static void main(String[] args) { try { someMethod(); } catch (NullPointerException e) { System.out.println("捕获到空指针异常: " + e.getMessage()); } } public static void someMethod() { String s = null; s.length(); } }
- 即使不使用
try - catch
块捕获运行时异常,程序也能通过编译,但是在运行时如果异常发生,会导致程序终止并打印异常堆栈信息。
编译时异常(非RuntimeException的Exception子类)
- 方法声明:
- 方法如果可能抛出编译时异常,必须在方法声明中使用
throws
关键字声明要抛出的异常类型。例如:
import java.io.FileInputStream; import java.io.FileNotFoundException; public void readFile() throws FileNotFoundException { FileInputStream fis = new FileInputStream("nonexistentfile.txt"); }
- 方法如果可能抛出编译时异常,必须在方法声明中使用
- 调用处:
- 调用一个声明抛出编译时异常的方法时,调用者必须显式处理该异常,有两种方式:
- 使用
try - catch
块捕获异常并处理。例如:
public class Main { public static void main(String[] args) { try { new Main().readFile(); } catch (FileNotFoundException e) { System.out.println("文件未找到异常处理: " + e.getMessage()); } } public void readFile() throws FileNotFoundException { FileInputStream fis = new FileInputStream("nonexistentfile.txt"); } }
- 如果不想在当前方法中处理异常,调用者也可以继续使用
throws
关键字将异常抛给上层调用者。例如:
public class Main { public static void main(String[] args) throws FileNotFoundException { new Main().readFile(); } public void readFile() throws FileNotFoundException { FileInputStream fis = new FileInputStream("nonexistentfile.txt"); } }
- 使用
- 如果调用者既不捕获异常也不向上抛出异常,代码将无法通过编译。
- 调用一个声明抛出编译时异常的方法时,调用者必须显式处理该异常,有两种方式: