检查时异常处理
使用try-catch处理异常
public class TestCheckedException {
public static void main(String[] args) {
readMyFile();
}
public static void readMyFile() {
FileReader fileReader = null;
try {
fileReader = new FileReader("d:/a.txt");
System.out.println("step1");
char ch = (char) fileReader.read();
System.out.println(ch);
} catch (FileNotFoundException e) { //子类异常在父类异常前面
System.out.println("step2");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
System.out.println("step3");
try {
if (fileReader != null) {
fileReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
运行时异常的处理
public class TestRuntimeException {
public static void main(String[] args) {
//ArithmeticException算术错误情形,如以零作除数
int a = 0;
int b = 1;
if (a != 0) {
System.out.println(b / a);
}
//NullPointerException 尝试访问 null 对象成员
String string = null;
if (string!=null){
System.out.println(string.length());
}
//ClassCastException 对象强制类型转换出错
Animal dog = new Dog();
if (dog instanceof Cat){
Cat cat = (Cat)dog;
}
//ArrayIndexOutOfBoundsException 数组下标越界
int[] arrs = new int[5];
int i = 5;
if (i<arrs.length){
System.out.println(arrs[i]);
}
//NumberFormatException 数字格式转换异常,如把"ab"转换成数字
}
}
class Animal{
}
class Dog extends Animal{
}
class Cat extends Animal{
}
使用throws进行异常处理
public class TestThrows {
public static void main(String[] args) throws IOException {
readMyFile();
}
public static void readMyFile() throws IOException {
FileReader fileReader = null;
fileReader = new FileReader("d:/a.txt");
System.out.println("step1");
char ch = (char) fileReader.read();
System.out.println(ch);
if (fileReader != null) {
fileReader.close();
}
}
}
手动抛出异常自定义异常
public class TestCustomException {
public static void main(String[] args) {
Person person = new Person();
person.setAge(-10);
}
}
class Person{
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
if (age<0){
throw new IllegalAgeException("年龄不能为负数");
}
this.age = age;
}
}
class IllegalAgeException extends RuntimeException{
public IllegalAgeException(){
}
public IllegalAgeException(String string){
super(string);
}
}