1.异常就是程序报错。
2.异常处理
(1)throw,将方法内部出现的异常抛出去给调用者。
(2)try...catch,直接捕获程序出现的异常。
3.自定义异常
自定义运行异常
class AgeIllegalRuntimeException extends RuntimeException {
public AgeIllegalRuntimeException(String message) {
super(message);
}
}
public class test {
public static void main(String[] args) {
try {
saveAge(223);
System.out.println("底层执行成功的!");
} catch (Exception e) {
e.printStackTrace();
System.out.println("底层出现了bug!");
}
}
public static void saveAge(int age) {
if (age > 0 && age < 150) {
System.out.println("年龄被成功保存: " + age);
} else {
// 抛出自定义异常,throw关键字
throw new AgeIllegalRuntimeException("age is illegal, your age is " + age);
}
}
}
自定义编译异常
class AgeIllegalException extends RuntimeException {
public AgeIllegalException(String message) {
super(message);
}
}
public class test {
public static void main(String[] args) {
try {
saveAge2(223);
System.out.println("底层执行成功的!");
} catch (Exception e) {
e.printStackTrace();
System.out.println("底层出现了bug!");
}
}
public static void saveAge2(int age)throws AgeIllegalException {
if (age > 0 && age < 150) {
System.out.println("年龄被成功保存: " + age);
} else {
// 抛出自定义异常,throw关键字
//throws 用在方法上,抛出方法内部异常
throw new AgeIllegalException("age is illegal, your age is " + age);
}
}
}
4.异常处理
(1)
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// 自定义运行时异常类
public class test {
public static void main(String[] args) {
try {
test1();
} catch (Exception e) {
System.out.println("警告当前操作有问题");
e.printStackTrace(); // 打印出这个异常对象的信息,记录下来。
}
}
public static void test1() throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = sdf.parse("2028-11-11 10:24:11");
System.out.println(d);
test2();
}
public static void test2() throws Exception {
// 读取文件
InputStream is = new FileInputStream("D:/meinv.png");
}
}
(2)
public class test {
public static void main(String[] args) {
// 需求:调用一个方法,让用户输入一个合适的价格返回为止。
// 无法修复
while (true) {
try {
System.out.println(getMoney());
break;
} catch (Exception e) {
System.out.println("请您输入合法的数字!");
}
}
}
public static double getMoney() {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请您输入合适的价格:");
double money = sc.nextDouble();
if (money >= 0) {
return money;
} else {
System.out.println("您输入的价格是不合适的!");
}
}
}
}