今天我们主要学习异常
一.异常
1.几个概念
1).Error:错误,不需要程序员管理
2).Exception:异常,所有异常的父类。
3).Runtime Exception:运行时异常,增强程序的健壮性就可以处理
一般运行时异常都会直接或者间接的继承自RuntimeException
4).CheckException:编译异常,如果程序一旦出现检查时异常,程序必须要经过处理,否则无法运行。
2.常见的运行时异常
1).空指针 NullPointerException
2).数组越界异常 ArrayIndexOutOfBoundsException
3).负数异常|数组的长度为负数异常 NegativeArraySizeException
4).数学异常 ArithmeticException
5).类型转换异常 ClassCastException
6).数字转换异常 NumberFormatException
public class ExceptionDemo01 {
public static void main(String[] args) {
/*1.空指针 NullPointerException
String s=null;
//增强程序的健壮性
if(s!=null){
s.length();
}else{
System.out.println("s是空的");
}*/
//2.数组越界 ArrayIndexOutOfBoundsException
//int[] arr=new int[3];
//System.out.println(arr[3]);
//3.负数异常 NegativeArraySizeException
//int[] arr=new int[-3];
//4.数学异常|分母为0异常
//System.out.println(2/0);
//5.类型转换异常 ClassCastException
/*Person p =new Student();
Teacher t=(Teacher)p;*/
//6.数字转换异常 NumberFormatException
String s="123abc";
System.out.println(Integer.valueOf(s));
//编译时异常
//InputStream is=new FileInputStream("D://test.txt");
System.out.println("呵呵嘿嘿哈哈哈或或哈哈或或");
}
}
3.异常的产生
之所以出现异常,是因为内部抛出了异常对象,这个异常对象的产生分为系统内部产生,或程序员手动抛出异常。
public static void test() throws Exception{
System.out.println("Hello World");
throw new Exception();
}
4.异常处理与捕获
对于编译(非运行)时异常( checked exception ),必须要对其进行处理,否则无法通过编译。处理方式有两种:
1)异常捕获 try catch finally
try{
//可能发生异常的代码
//如果发生了异常能,那么异常过后的代码将不会被执行
}catch (XXxException e){
//异常处理代码
}catch (Exception e){
//异常处理代码
}fianlly{
//不管有没有发生异常,finally语句块都会被执行
}
5.注意
1).如果try中的代码出现异常,下面的代码不会执行,直接执行对应的catch中的代码
2).一个try至少存在一个或者多个catch
3).catch中捕获异常的顺序从小到大写
6.向外 声明( 抛出) 异常 throws
public static void test()throws Exception{
//可能发生异常的代码
//如果发生了异常,那么异常后面的代码都不会被执行
}
在产生异常的方法声明后面写上 throws 某一个 Exception 类型,如 throws Exception,将异常抛出到外面一层去。
异常与重写:子类声明的异常范围不能超出父类的异常范围
7.使用自定义的异常
所谓自定义异常,通常就是定义一个类,去继承 Exception 类或者它的子类。因为异常必须直接或者间接地继承自 Exception 类。通常情况下,会直接继承自 Exception 类,一般不会继承某个运行时的异常类。
public class MyException extends Exception{
public MyException(){
super();
}
public MyException(String Message){
super(message);
}
}
使用自定义异常一般有如下步骤:
1).通过继承java.lang.Exception类声明自己的异常类
2).在方法适当的位置生成自定义异常的实例,并用throw语句抛出
3).在方法声明部分用throws语句声明该方法可能抛出的异常