为什么学习异常?
异常一旦出现没有处理,程序就会退出jvm虚拟机而终止。
//介绍异常
public static void main(String[] args) {
//数组越界异常 ArrayIndexOutOfBoundsException
int[] arr={1,2,3,4};
System.out.println(arr[5]);
//空指针异常 NUllPointerException
String name = null;
System.out.println(name.length());
//类转换异常 ClassCastException 实现类或继承关系是可以转换的
Object o=23;
String s=(String) o;
//数字操作异常ArithmeticException
int c = 10/0;
//数字转换异常 NumberFormatException
String number ="23a";
Integer integer = Integer.valueOf(number);
}
try+catch快捷键 alt+enter 或者 ctrl+alt+t
自定义一个运行时异常
先定义一个异常类,继承RuntimeExeception
public class AgeIllegalException extends RuntimeException{
public AgeIllegalException() {
}
public AgeIllegalException(Throwable cause) {
super(cause);
}
}
public static void main(String[] args) {
try {
saveAge(173);
System.out.println("底层执行成功");
} catch (Exception e) {
e.printStackTrace();
System.out.println("底层出现bug");
}
}
public static void saveAge(int age){
if (0<=age && age <=150){
System.out.println("年龄输入正确");
}else{
throw new AgeIllegalException();
}
}
自定义一个编译时异常
先定义一个异常类,继承Exception
public class AgeIllException extends Exception{
public AgeIllException() {
}
public AgeIllException(Throwable cause) {
super(cause);
}
}
public static void main(String[] args) {
try {
saveAge(234);
System.out.println("底层代码正确");
} catch (AgeIllException e) {
e.printStackTrace();
System.out.println("底层代码出现错误");
}
}
public static void saveAge(int age) throws AgeIllException{
if (age >=0 && age<= 150){
System.out.println("年龄输入正确");
}else{
throw new AgeIllException();
}
}
throw是抛出异常对象用在方法内部
throws也是抛出异常,用在方法上,抛出方法内部异常。
问题如果特别严重,就抛出编译时异常,会提示程序员。
如果问题比较轻,就抛出运行时异常。
异常时查询系统bug的关键参考信息
异常处理案例,建议方法都抛出Exception异常,最后的方法调用者再try-catch捕获异常
public static void main(String[] args) {
try {
test1();
System.out.println("调用成功");
} catch (Exception e) {
e.printStackTrace();
System.out.println("程序出现bug");
}
}
public static void test1() throws Exception {
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.parse("2023-12-23 23:09:09");
test2();
}
private static void test2() throws Exception {
InputStream is=new FileInputStream("D:/mainv.png");
}
第二种异常处理机制: 在最外层捕获异常,并尝试修复
案例:输入正确价格 (提高代码的健壮性)
public static void main(String[] args) {
while (true){
try {
System.out.println(getMoney());
break;
} catch (Exception e) {
System.out.println("请输入正确格式");
}
}
}
public static Double getMoney(){
while (true){
System.out.println("请输入价格:");
Scanner sc=new Scanner(System.in);
double v = sc.nextDouble();
if (v>0){
return v;
}else {
System.out.println("您输入价格不合适:");
}
}
}