1、异常的继承
(1)Throwable 是异常类的父类,Error和Exception为子类:
Error 子类 代码不能处理 xxxError
Excaption 子类 代码能处理的 xxxException
(2)运行时的异常有:(越界,空指针,内存溢出等)
RuntimeException java虚拟机正常运行期间抛出的异常
NullPointerException 空指针异常
ArrayIndexOfBoundsException 数组越界异常
StringIndexOfBoundsException 字符串越界异常
ArithmeticException 运算条件异常
编译时产生的异常有:
IOException I/O错误时引起的异常
FileNotFoundException 系统找不到路径
InterruptedException 正在执行的线程中断异常
SQLException SQL数据库异常
2、运行时异常:不强制处理,如果代码写的严谨,可以避免运行时异常的产生
编译时异常:产生的异常必须处理
3、处理异常
(1)throws抛出异常(声明异常)
(2)try-catch块捕获异常
异常代码块:在日志文件中保存堆栈信息,对于其他非编译人员可以翻译异常信息,检查代码时可以直接打印堆栈信息
//运行时异常
public static void test1() {
String[] names=null;
System.out.println(names[0].substring(0));
int[] num= {2};
System.out.println(num[1]);
}
//编译时异常
public static void test2() throws FileNotFoundException {
FileReader fr=new FileReader("a.txt");
}
//打印堆栈信息
public static void test3() {
try {
FileReader fr=new FileReader("a.txt");
System.out.println("???");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
}
}
4、try-catch 多种格式
try-catch
try-catch-finally
try-catch-catch----finally
try-finally 语法没错,编译错误
一个try可以由多个catch块捕获,catch块中父类可以捕获多个try块中的异常。
多个try块不能由多个catch块捕获
try-catch可以嵌套try-catch使用
public static int test6() {
int i=0;
try { //先执行try,后执行finally
return i++;
}catch(Exception e){
return 2;
}finally {
i++;
System.out.println(i);
System.out.println("end"); //一定会执行finally
return i; //覆盖try块中的return
}
}
//在 finally块中,尽量不要写return,有时候会屏蔽异常代码
public static String test7(String name) {
try {
name.length();
}finally {
return name+"hello";
}
}
5、自定义异常
extends Exception
super(异常信息);
用if(){throw异常类对象}
//自定义异常类:继承现有的异常
public interface Message{
//ageMessage
String ageMessage=请输入正确的范围数字(1-150)”;
}
//编译
public class AgeException extends Exception{
public Ageexception(){
//调用父类带参的构造方法,初始化错误信息
super(“请输入正确的范围数字(1-150)”);
}
}
//使用自定义的异常
if(age<1||age>150)
throw new AgeException(); //抛出异常
6、方法重写的异常(编译时异常)
子类方法重写父类方法的异常规则:
异常要小于等于父类的(指编译时异常,和运行时异常没有关系)
小于等于父类指个数、继承关系
class A{
public void test()throws IOException,SQLException{
}
public void test2(){
}
}
public class Demo4 extends A{
public void test()throws IOException{
}
public void test2()throws RuntimeException{
}