异常注意事项
1.父类方法没有抛出异常,子类覆盖父类该方法时也不可抛出异常。---重点掌握
此时子类产生该异常,只能捕获处理,不能声明抛出
package com.itheima.five;
public class Demo05Throw {
public static void main(String[] args) {
int[] array = {100, 200, 300};
array = null;
int value = getValue(array, 5);
System.out.println("main方法中正确获取到数组元素值: " + value);
}
public static int getValue(int[] array, int index) {
if (array == null) {
throw new NullPointerException("脑子被xxx踢了,数组是: "+array+", 无法获取元素了");
}
if (index < 0 || index >= array.length) {
throw new ArrayIndexOutOfBoundsException("你个不长眼的,数组索引: "+index+"超出范围了,无法获取元素");
}
int value = array[index];
System.out.println("getValue方法中正确获取到数组元素值: " + value);
return value;
}
}
二
package com.itheima.five;
import java.io.FileNotFoundException;
import java.text.ParseException;
public class Demo08DuoTryCatch {
public static void main(String[] args) {
try {
a();
b();
} catch (ParseException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
try {
a();
b();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void a() throws ParseException {
throw new ParseException("解析文件失败", 2);
}
public static void b() throws FileNotFoundException {
throw new FileNotFoundException("文件不存在");
}
}
三
package com.itheima.five;
public class UserNameRegisterException extends Exception {
public UserNameRegisterException() {
}
public UserNameRegisterException(String message) {
super(message);
}
}