- 异常机制
java是采用面向对象的方式来处理异常。 处理过程:
(1)抛出异常:在执行一个方法时,若若发生异常,则这个方法生成代表该异常的一个对象,停止当前执行路径,并把异常对象提交给JRE
(2)捕获异常:JRE得到该异常后,寻找相应的代码来处理该异常。JRE在方法的调用栈种查找,从生成异常的方法开始回溯,直到找到相应的异常处理代码为止。 - 异常的分类
- Runtime Exception运行时异常
(1)NullPointerException异常
空指针异常
package cn.sxt.exception;
public class TestException {
public static void main(String[] args) {
String str = null;
str.length();
}
}
(2)ClassCastException异常(强制转型发生的错误)
package cn.sxt.exception;
public class TestException {
public static void main(String[] args) {
Animal dd = new Dog();
Cat c =(Cat)dd;
}
}
class Animal{
}
class Dog extends Animal{
}
class Cat extends Animal{
}
(3)ArrayIndexOutOfBoundsException异常(数组越界)
- checked Exception已检查异常
package cn.sxt.exception;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
/**
* 异常处理Try,catch
* @author LLI
*
*/
public class Test01 {
public static void main(String[] args) {
FileReader reader =null;
try {
reader = new FileReader("e:/a.txt");
char c1 = (char)reader.read();
} catch (FileNotFoundException e) {//子类异常在父类异常前面
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
- 自定义异常
package cn.sxt.exception;
/**
* 自定义异常
* @author LLI
*
*/
public class Test02 {
public static void main(String[] args) {
Person person = new Person();
person.setAge(-10);
}
}
class Person{
private int age;
private int getAge() {
return age;
}
void setAge(int age) {
if(age<0) {
throw new IllegalAgeException("年纪不合格");
}
this.age = age;
}
}
class IllegalAgeException extends RuntimeException{
public IllegalAgeException() {
// TODO Auto-generated constructor stub
}
public IllegalAgeException(String msg) {
super(msg);
}
}