Java中exception异常详解说明
下文笔者讲述java中Exception异常的简介说明,如下所示
Exception异常分类
一、Checkedexception
非RuntimeException
二、Uncheckedexception
RuntimeException
注意事项:
java中所有异常类可以说都是继承于Exception类
Exception类测试
public class ExceptionTest {
public static void main(String[] args) {
int c = 0;
try {
int a = 8;
int b = 0;
c = a / b;
System.out.println("test information!");
}
catch (ArithmeticException e) {
e.printStackTrace();
}
finally{
System.out.println("finally");
}
System.out.println(c);
}
}
----运行以上代码,将输出以下信息-----
java.lang.ArithmeticException: / by zero
at test10.ExceptionTest.main(ExceptionTest.java:9)
finally
0
自定义抛出异常throw new Exception()
public class Exception2 {
public void method() throws Exception{
System.out.println("test java265.com");
throw new Exception();
}
public static void main(String[] args) {
Exception2 test = new Exception2();
try {
test.method();
}
catch (Exception e) {
e.printStackTrace();
}
finally{
System.out.println("finally");
}
}
}
-----运行以上代码,将输出以下信息
test java265.com
java.lang.Exception
at test10.Exception2.method(Exception2.java:6)
at test10.Exception2.main(Exception2.java:11)
finally
对于非运行时异常(checkedexception)
必须要对其进行处理
处理方式有两种
第一种是使用try..catch…finally进行捕获
第二种是在调用该会产生异常的方法所在的方法声明throwsException。
对于运行时异常(runtime exception)
可不对其进行处理 笔者建议这种情况不对其处理
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


