1.异常(例外、差错):exception
基本写法:
try{
语句组
}catch(Exception ex){
异常处理语句;
}
例:
import java.io.*;
public class Test
{
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();
}
}
}
2.Java中的异常处理
(1)抛出(throw)异常
throw 异常对象;
(2)运行时系统在调用栈中查找
(3)捕获(catch)异常的代码
try{
语句组;
}catch(异常类名,异常形式参数名){
异常处理语句组;
}finally{
异常处理语句组;
}
3.异常的分类
Throwable
(1)Error:JVM的错误
(2)Exception:异常
Exception类:
构造方法:
public Exception();
public Exception(String message);
Exception(String message, Throwable cause);
方法:
getMessage()
getCause()
printStackTrace()
4.多异常处理
子类异常要排在父类异常的前面
finally语句
无论是否有异常都要执行
例:
public class Test
{
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(1);//23
foo(0);//134
System.out.println(output);
}
}
5.受检的异常
Exception分两种
(1)RuntimeException及其子类
(2)受检的异常(checked Exception)
受检的异常:
(1)catch
(2)throws