异常是程序执行期间发生的各种意外或错误。
1、分类:
1)编译错误:
由于没有遵循Java语言的语法规则而产生的,这种错误要在编译阶段排除,否则程序不可能运行。
2)逻辑错误:
指程序编译正常,也能运行,但结果不是人们所期待的。
3)运行时错误:
指程序运行过程中出现了一个不可能执行的操作,就会出现运行时错误,运行时错误有时也可以由逻辑错误引起。
2、通常产生的异常情况:
1) 用户输入出错
2) 所需文件找不到
3) 运行时磁盘空间不够
4) 内存不够
5) 算术运算错 (数的溢出,被零除…)
6)数组下标越界
3、异常类结构图:
4、异常的处理机制
抛出(throw)异常:
1 由系统自动抛出异常:
在程序运行过程中,如果出现了可被Java运行系统识别的错误,系统会自动产生与该错误相对应的异常类的对象,即自动抛出。
2 人为异常抛出:
① 在方法头写出需要抛出的异常(利用throws语句)
class Throws_Exp{
public static void main(String[] args) throws ArithmeticException,ArrayIndexOutOfBoundsException
{
int a=4,b=0,c[]={1,2,3,4,5};
System.out.println(a/b);
System.out.println(c[a+1]);
System.out.println(“end”);
}
}
② 在方法体内抛出异常(利用throw语句)
class Throw_Exp3 {
public static void main(String[] args) {
int a=5,b=0,c[]={1,2,3,4,5};
System.out.println(“Before throw”);
if(b==0)
throw (new ArithmeticException ());
System.out.println(a/b);
if(a>4)
throw (new ArrayIndexOutOfBoundsException());
System.out.println(a/b);
}
}
<span style="font-size:14px;"></span>
捕捉(catch)异常:
try – catch语句块格式:
try
{
//在此区域内或能发生异常;
}catch(异常类1 e1)
{ //处理异常1; }
…
catch(异常类n en)
{ //处理异常n; }
[finally
{ //不论异常是否发生,都要执行的部分; }
]
eg:
public class ExceptionDemo {
public static void main(String[] args) {
ExceptionDemo ed=new ExceptionDemo();
ed.arrayindexException();
}
public void arrayindexException(){
try{
int[] a=new int[2];
for(int i=1;i<3;i++){
a[i]=i;
}
String s=null;
int length=s.length();
}catch(ArrayIndexOutOfBoundsException e){
String message=e.getMessage();
System.out.println("数组下标越界:"+message);
}catch(NullPointerException j){
String message=j.getMessage();
System.out.println("空指针异常:"+message);
}
}
}
5、用户自定义的异常类
满足需求而自己定义来抛出,捕捉的异常类。继承Exception异常类。
(1)用户自定义的异常类必须是Throwable类或Exception类的子类。
(2)自定义的异常类,一般只要声明两个构造方法,一个是不用参数的,另一个以字符串为参数。作为构造方法参数的字符串 应当反映异常的信息。
(3)自定义异常类格式
class MyException extends Exception{
…
}
注:用户定义的异常同样要用try–catch捕获,但必须由用户自己抛出 throw new MyException().
class Exception_exp{
public static void main(String[] args){
try {
System.out.println("2+3="+add(2,3));
System.out.println("-8+10="+add(-8,10));
}catch (Exception e){
System.out.println("Exception is "+e);
}
}
public static int add(int n,int m) throws UserException {
if (n<0|| m<0) throw new UserException();
return n+m;
}
}
class UserException extends Exception{
UserException(){
super("数据为负数");
}
}