异常的分类
运行期异常:
- 程序运行时可能产生的异常,可以处理,也可以不处理,如果程序员不处理,交给系统默认的异常处理程序处理,但这样会导致程序中断,所以最好还是处理下
编译期异常
- 编译时表现为语法错误,必须处理,否则编译通不过
RuntimeException:所有运行期异常的超类
Exception:所有异常的超类
异常的处理
通过try catch语句捕获异常
try{
被监视的程序代码
}catch(异常类型1 标识符){
异常处理代码
}catch(异常类型 2 标识符){
异常处理代码
}
...
finally{
不管异常是否发生都会执行的代码(一般用于释放资源,例如关闭文件等),除非JVM退出
}
注意:可以有多个 catch 子句,只要有一个匹配上,执行完其中的异常处理代码,整个try catch就结束了
声明异常
通过throws关键字将异常抛出,可以抛多个异常,异常类名中间用“ , ”隔开
public void 方法名(参数列表) throws 异常类名1,异常类名2...{ }
代码示例
public class ExceptionTest {
public static void main(String[] args) {
try {
int a=99;
Scanner scan = new Scanner(System.in);
System.out.println("请输入一个整数作为除数:");
int b = scan.nextInt();
int c = a/b;
System.out.println("c="+c);
//return; //退出方法
System.exit(0); //退出JVM 参数0表示正常退出
}
catch(InputMismatchException e){
System.err.println("输出不匹配");
}
catch (ArithmeticException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
System.err.println("除数不能为0");
}
finally{
System.out.println("无论发生什么,我都会执行");
}
//getInt();
//常见的异常
//String[] arr=new String[10];
//空指针异常
//System.out.println(arr[0].length());
//数组越界异常
//System.out.println(arr[10]);
//字符串索引越界
//System.out.println("hello".charAt(9));
//类型转换异常
//Object obj = new String("hello");
//Integer i =(Integer)obj;
/*try {
getInt2();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
System.out.println("----------");
}
public static void getInt(){
try {
byte[] buf = new byte[1024];
System.in.read(buf);
String s = new String(buf); //通过byte数组新建一个新的String
s = s.trim(); //去掉字符串前后的空白符
int i = Integer.parseInt(s); //将数字字符串转换成整型数
System.out.println("i="+i);
}
catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
}
//异常处理方式2:声明异常
public static void getInt2() throws IOException,NumberFormatException {
byte[] buf = new byte[1024];
System.in.read(buf);
String s = new String(buf); //通过byte数组新建一个新的String
s = s.trim(); //去掉字符串前后的空白符
int i = Integer.parseInt(s); //将数字字符串转换成整型数
System.out.println("i="+i);
}
}