文章目录
- java异常的捕获和抛出
- 异常的定义:
- 与error的区别:
- 对exception的处理
- 捕获异常
- 抛出异常
java异常的捕获和抛出
异常的定义:
在万物皆对象的Java里,异常也可以看作对象.并定义了一个基类java.lang.Throwable作为所有异常的超类.
异常被分为两大类: error exception
exception,表例外的情况.指程序在运行时出现的各种意外状况.
异常发生在程序运行期间,注意异常要区别于错误error.
与error的区别:
error一般是比较严重的错误,是程序无法控制和处理的,遇到这种情况JVM一般会终止线程;而异常exception通常是可以被程序处理掉的,除了完全解决.只要我们在程序执行过程中,捕获并抛出异常,程序也还是可以继续往下执行.
对exception的处理
捕获异常
(1)try:监控区域
(2)catch:捕获异常
(3)finally:善后处理(不是必备)
快捷键:Ctrl + Alt +T可以选择
public class test_01 {
public static void main(String[] args) {
int a = 1;
int b = 0;
try { // try 监控区域
System.out.println(a/b);
} catch (Exception e) { // 捕获异常 catch(想要捕获的异常类型)
//e.printStackTrace(); 输出堆栈跟踪,也就是咋们运行时错误出现的错误分析
System.out.println("程序出现异常,b不能为0");
}finally {//处理一些善后工作
System.out.println("finnally");
}
}
}
也可以有多重catch,但是想要捕获的异常类型必须逐渐递进
package com.heima.test;
public class test_01 {
public static void main(String[] args) {
int a = 1;
int b = 0;
try { // try 监控区域
System.out.println(a/b);
} catch (Exception e) { // catch(想要捕获的异常类型) 捕获异常
//e.printStackTrace(); 输出堆栈跟踪,也就是咋们运行时错误出现的错误分析
System.out.println("程序出现异常,b不能为0");
}catch(Error e){
System.out.println("error");
}catch (Throwable e){
System.out.println("throwable");
} finally {//处理一些善后工作:假设io、资源的关闭
System.out.println("finnally");
}
}
}
抛出异常
(1)throw:用在方法体内,表示抛出异常,由方法体内的语句处理。是当程序出现某种逻辑错误时由程序员主动抛出某种特定类型的异常是,具体向外抛异常的动作,所以它是抛出一个异常实例。
package com.heima.test;
public class test_throw {
public static void main(String[] args) {
new test_throw().test(1,0);
}
public void test(int a,int b){
if (b==0){
throw new ArithmeticException();
}
}
}
(2)throws:用在方法声明后面,表示抛出异常,由该方法的调用者来处理。主要是声明这个方法会抛出这种类型的异常,使它的调用者知道要捕获这个异常。
好处:如果明知道这个方法存在异常,可以出动抛出,然后在更高级进行捕获,这样程序不会停止,会继续执行下去,我们也可以在catch对异常进行处理。
package com.heima.test;
public class test_throw {
public static void main(String[] args) {
try {
new test_throw().test(1,0);
} catch (ArithmeticException e) {
//e.printStackTrace();
System.out.println("可以在这里进行一些处理");
} finally {
System.out.println("进行善后工作");
}
}
public void test(int a,int b) throws ArithmeticException{
if (b==0){
throw new ArithmeticException();
}
}
}