异常,又称例外、差错、违例,对应着Java运行错误处理机制
基本写法
try{
语句组
}catch(Exception ex){
异常处理语句;
}
示例:ExceptionForNum.java
import java.io.*;
public class ExceptionForNum
{
public static void main(String[] args)
{
try{
BufferedReader in = new BufferedReader(new InputStreamReader( System.in ) );
System.out.print("Please input a number: ");
String s = in.readLine();
int n = Integer.parseInt( s );
}catch(IOException ex){
ex.printStackTrace();
}catch(NumberFormatException ex){
ex.printStackTrace();
}
}
}
传统语言如何处理
在一些传统语言(如C语言中)
if语句来判断是否出现了例外
全程变量ErrNo
但这有几个缺点:
正常处理与异常处理代码同样处理,可读性差
每次调用一个方法时都进行错误检查,可维护性差
错误由谁处理不清,职责不清
Java中的异常处理
抛出(throw)异常
运行时系统在调用栈中查找,从生成异常的方法开始进行回溯,直到找到
捕获(catch)异常的代码
相关语句
抛出异常
throw 异常对象
捕获异常
try{
语句组
}catch(异常类名,异常形式参数名){
异常处理语句组;
}catch(异常类名,异常形式参数名){
异常处理语句组;
}finally{
异常处理语句组;
}
其中,catch语句可以0至多个,可以没有finally语句
异常的分类
• Throwable
Error: JVM的错误
Exception: 异常
• 一般所说的异常是指Exception及其子类
Exception类
构造方法
• public Exception();
• public Exception(String message);
• Exception(String message, Throwable cause) ;
方法
• getMessage()
• getCause()
• printStackTrace()
多异常的处理
• 子类异常要排在父类异常的前面
• finally语句
无论是否有异常都要执行,即使其中有break,return等语句
• 在编译时,finally部分代码生成了多遍
例 TestTryFinally.java
public class TestTryFinally {
public static String output = "";
public static void foo(int i) {
try {
if (i == 1) {
throw new Exception();
}
output += "1";
} catch(Exception e) {
output += "2";
return;
} finally {
output += "3";
}
output += "4";
}
public static void main(String args[]) {
//foo(0);
//System.out.print(output + " ");
foo(1);
System.out.println(output);
}
}
受检的异常
• Exception分两种
RuntimeException及其子类,可以不明确处理
否则,称为受检的异常(checked Exception)
• 受检的异常,要求明确进行语法处理
要么捕(catch)
要么抛(throws):在方法的签名后面用throws xxxx来声明
• 在子类中,如果要覆盖父类的一个方法,若父类中的方法声明了throws异常,则子类的方法也可以throws异常
• 可以抛出子类异常(更具体的异常),但不能抛出更一般的异常
• 示例: ExceptionTrowsToOther.java
import java.io.*;
public class ExceptionTrowsToOther{
public static void main(String[] args){
try{
System.out.println("====Before====");
readFile();
System.out.println("====After====");
}catch(IOException e){ System.out.println(e); }
}
public static void readFile()throws IOException {
FileInputStream in=new FileInputStream("myfile.txt");
int b;
b = in.read();
while(b!= -1) {
System.out.print((char)b);
b = in.read();
}
in.close();
}
}
try…with…resource
try(类型 变量名 = new 类型() ){
...
}
• 自动添加了finally{ 变量.close(); }
不论是否出现异常,都会执行
示例: TryWithResourcesTest.java
import java.io.*;
class TryWithResourcesTest {
public static void main(String ... args)
throws IOException
{
String path = "c:\\aaa.txt";
System.out.println( ReadOneLine1( path ) );
System.out.println( ReadOneLine2( path ) );
}
static String ReadOneLine1(String path){
BufferedReader br=null;
try {
br=new BufferedReader(new FileReader(path));
return br.readLine();
} catch(IOException e) {
e.printStackTrace();
} finally {
if(br!=null){
try{
br.close();
}catch(IOException ex){
}
}
}
return null;
}
static String ReadOneLine2(String path)
throws IOException
{
try(BufferedReader br= new BufferedReader(new FileReader(path))){
return br.readLine();
}
}
}