JAVA提供了异常处理的语法结构来对异常进行处理。主要有两种方式:
- try-catch-finally块:在可能出错的代码块中使用try关键字包围,在对应的catch块中捕获异常进行处理,finally块确保关键的资源释放等操作。
| |
public class HandleException { |
| |
|
| |
public static void main(String[] args) { |
| |
BufferedReader br = null; |
| |
try { |
| |
br = new BufferedReader(new FileReader("file.txt")); |
| |
|
| |
} catch (IOException e) { |
| |
e.printStackTrace(); |
| |
} finally { |
| |
if(br != null) { |
| |
try { |
| |
br.close(); |
| |
} catch(IOException e) { |
| |
e.printStackTrace(); |
| |
} |
| |
} |
| |
} |
| |
} |
| |
} |
- throws声明:在方法签名中使用throws关键字声明该方法可能抛出的异常类型,调用方法的地方需处理这些异常。
| |
public class ThrowsDemo { |
| |
|
| |
public void readFile(String file) throws IOException { |
| |
|
| |
} |
| |
|
| |
public static void main(String[] args) { |
| |
ThrowsDemo td = new ThrowsDemo(); |
| |
try { |
| |
td.readFile("file.txt"); |
| |
} catch (IOException e) { |
| |
|
| |
} |
| |
} |
| |
} |