一、常见异常
1.数据越界异常: ArrayIndexOutOfBoundsException
比如:
int[] a=new int[5];
a[5]=5;
2.字符串越界:StringIndextOutOfBoundsException
String s="abcd";
s.charAt(4);
3.算数异常: ArithmeticException
int a=10;
int b=0;
int c=a/b;
4.空指针异常:NullPointerException
String s=null;
s.length();
5.类型转换异常:ClassCastException
Object s="abcd";
Integer a=(Ineger) s;
6.数字格式化异常:NumberFormatException
int a =Integer.parseInt("abc");
二、异常的结构
Error类是内存的问题,不是程序中主要处理的问题
Exception类 分为编译期间错误,和运行期间错误
三、异常的解决方法
1.抛出throw,throws
throws: 在方法参数列表后面,用来声明此方法可能会出现异常,谁调用,谁来处理。运行期异常不主动提示,检查期异常会主动报错。
throw :在方法体内,当不满足某种条件时,会主动抛出异常。程序不再向后执行
//异常的处理
try代码块 尝试
catch()try代码块里出现异常判断是否是()里的异常类型,如果是则进行catch里的代码块。
finally{}代码块 必须而且是最后执行的代码块。
*/try {
int []i=new int[5];
i[5]=0;
}catch (ArrayIndexOutOfBoundsException a){
System.out.println("索引");
}
2.解决try catch
try代码块 尝试 catch()try代码块里出现异常判断是否是()里的异常类型,如果是则进行catch里的代码块。 finally{}代码块 必须而且是最后执行的代码块。
try {
int []i=new int[5];
i[5]=0;
}catch (ArrayIndexOutOfBoundsException a){
System.out.println("索引");
}
四、自定义异常:
java API中定义的标准异常类,都是与语法有关的(例如索引越界,空指针),但是程序不可能满足业务的需求,想以异常的类型解决问题,就需要我们自己编写一个异常类(自定义异常)。
以处理分数为例:100-90为A 80-90为D 80-0为C
public class ScoreExceptionForExceptionDemo extends Exception{
//自定义异常
public ScoreExceptionForExceptionDemo(String error) {
super(error);
}
}
public class ExceptionDemo {
//异常的使用情况,不满足条件主动抛出异常。
public static void main(String[] args) {
try {
char index = checkScore(110);
System.out.println(index);
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
}
public static char checkScore(int score) throws Exception {
//分数处理异常
if(score<0||score>100)
{
//借用io异常的异常名,创建自己的异常类型,在main方法中处理,否则程序无法继续执行.
throw new ScoreExceptionForExceptionDemo("分数超出范围");//抛出后需要声明此方法可能会出错;
}
//基本分数处理
if(score>=90)
{
return 'A';
}
else if (score>=80)
{
return 'B';
}
else {
return 'c';
}
}
}