- 前言
- 一、Java异常
- 1、抛出异常
- 2、捕获异常
- 3、异常类
- a、For RuntimeException
- b、For CheckedException
- 4、自定义异常
- 5、异常机制建议
- 总结
一、Java异常 1、抛出异常该篇指针对入门,学习Java异常基本知识。
2、捕获异常1)程序发生异常,如非法运算、文件不存在、I/O流异常等。
2)封装异常对象,Java作为面向对象的高级语言,当遇到异常时,将关于异常的一些信息封装到对应的异常对象中。
3)停止当前执行路径,并将异常交给JRE。
1)JRE获得异常对象
2)寻找相应代码来处理异常,JRE在函数调用栈中进行回溯寻找,直到找到相应异常处理代码为止。
注:JRE就是通过程序抛出异常,JRE捕获异常来对异常进行一个完整处理。
3、异常类a、For RuntimeException这是异常类继承关系大致图。
只需了解Throwable类为开始,
1)Error,这一般是一些关于硬件的error。
2)Exception,主要认识的异常类,分为RuntimeException和CheckedException(其它要检测异常的统称)。
1)NULLException,一般用if来做一个判断对象是否为空来解决。
public static void main(String[] args) {
String str = null;
char[] chs;
if (str != null)
chs = str.toCharArray();
}
2)ClassCastException,强转类出错。通过instanceof来判断。
public static void main(String[] args) {
List arr = new ArrayList<>();
linkedList ll = null;
if(arr instanceof linkedList)
ll = (linkedList)arr;
}
3)NumbeFormatException,通过正则表达式判断。
public static void main(String[] args) {
String str = "123ab";
Pattern p = Pattern.compile("^\d+$");
Matcher m = p.matcher(str);
Integer i = 0;
if(m.matches())
i = Integer.parseInt(str);
}
b、For CheckedException
1)try…catch…
public void testCheckedException() {
FileReader reader = null;
try {
//文件可能找不到
reader = new FileReader("d:\a.txt");
//读的时候可能出现I/O异常
char ch = (char) reader.read();
} catch (FileNotFoundException e) {//匹配文件找不到异常
e.printStackTrace();
} catch (IOException e) {//匹配I/O异常
e.printStackTrace();
} finally {//不管有没有exception,都要执行关闭文件,以便其它线程使用该文件。
if (reader != null) {//NULLException处理方法
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2)throws
public static void testThrowException() throws IOException {
FileReader reader = new FileReader("d:\a.txt");
char ch = (char) reader.read();
if (reader != null) {
reader.close();
}
}
public static void main(String[] args) throws IOException {
testThrowException();
}
4、自定义异常
只需继承相应的异常类即可变成异常类,封装自己的异常信息。
package com.xhu.java;
public class DefineException {
//异常类的封装
static class IllegalAgeException extends Exception {
//异常类构造所必要的构造函数
public IllegalAgeException(String msg) {
super(msg);
}
}
//人物类,通过setAge的throws来控制未成年
static class Person {
int age;
public int getAge() {
return age;
}
public void setAge(int age) throws IllegalAgeException {
if (age < 18) {
throw new IllegalAgeException("未成年不能加入!");
}
this.age = age;
}
}
public static void main(String[] args) {
Person p = new Person();
//可try...cathch...,也可在main函数甩出异常,把异常交给JRE。
try {
p.setAge(17);
} catch (IllegalAgeException e) {
System.out.println(e.getMessage());
System.exit(0);
}
System.out.println("继续执行代码");
}
}
5、异常机制建议
1)只有在异常情况下使用异常机制
2)用多个catch去匹配try中出现的多种异常,而不是用小粒度的try…catch.导致程序可读性很差。
3)异常往往在高层处理,低层直接抛出异常,到高层调用时处理。
1)异常入门
2)抛出异常 + 捕获异常
3)Throwable、Error、Exception、RuntimeException(UncheckedException)、CheckedException的关系(像二叉树式的继承关系)
4)try…catch…finally || throws
5)自定义异常:throw new Exception() + throws
6)异常使用建议,异常情况、粒度、高层处理。



