1. 定义
Exception(异常)
代表程序可能出现的问题
- 运行时异常:RuntimeException及其子类,指的编译阶段不会出现错误提醒,运行时出现的异常(如:数组索引越界异常)
- 编译时异常:编译阶段出现的错误提醒(如:日期解析异常)
- Error:系统级别的异常,如果系统出现了问题,会通过Error对象呈现
2. 异常代码示例
2.1 运行时异常
// 运行时异常
public class ExceptionDemo1 {
public static void main(String[] args) {
show();
}
public static void show(){
int[] arr = {1,2,3};
System.out.println(arr[3]);
}
}
运行结果
可以看到异常报错,判断是否为运行时时异常,按住Ctrl和右击红框内ArrayIndexOutOfBoundsException查看其是否继承RuntimeException类
ArrayIndexOutOfBoundsException继承IndexOutOfBoundsException类,而IndexOutOfBoundsException类继承RuntimeException,因此该异常是一个运行时异常
其它运行时异常
10/0的异常
// 运行时异常——10/0
public class ExceptionDemo1 {
public static void main(String[] args) {
show();
}
public static void show(){
System.out.println(10/0);
}
}
运行结果
空指针异常
// 运行时异常——空指针异常
public class ExceptionDemo1 {
public static void main(String[] args) {
show();
}
//运行时异常
public static void show(){
String str=null;
System.out.println("字符串为:"+str);
System.out.println("字符串长度为:"+str.length());
}
}
运行结果
2.2 编译时异常
// 编译时异常-时间解析
public class ExceptionDemo1 {
public static void main(String[] args) {
show();
}
//运行时异常
public static void show(){
String str=null;
System.out.println("字符串为:"+str);
System.out.println("字符串长度为:"+str.length());
}
}
该异常的解释是:
java.text.ParseException 是 Java 中的一个异常类,用于表示解析文本时发生的错误。当你使用 java.text 包中的类(如 SimpleDateFormat)将字符串转换为日期或其他格式化对象时,如果输入的字符串不符合预期的格式,就会抛出 ParseException。
3. 异常的基本处理
抛出异常(throws)和捕获异常(try…catch)
3.1 抛出异常
在方法上使用throws关键字,可以将方法内部出现的异常抛出去给调用者处理
方法 throws 异常1, 异常2, 异常3 ...{
...
}
3.2 捕获异常(try …catch)
直接捕获程序出现的异常
try{
//监视可能出现的异常的代码
}catch(异常类型1 变量){
//处理异常
}catch(异常类型2 变量){
//处理异常
}
3.3 异常处理示例
这里选用日期解析异常
3.3.1 抛出异常
可以将选中异常出现的地方,按住Alt,然后按回车,然后再按一次回车
然后选第一个,会在show()函数后面抛出异常,抛出给调用者
接着可以将main函数继续抛出异常
运行后的结果
3.3.2 捕获异常
在main函数中来捕获show函数运行的异常,并打印异常
在代码中将解析的日期格式改变一下
运行结果