Java 异常
2019-08-06 本文已影响10人
一亩三分甜
异常:就是程序在运行时出现不正常情况。
异常由来:问题也是现实生活中一个具体的事物,也可以通过java的类的形式进行描述。并封装成对象。其实就是java对不正常情况进行描述后的对象体现。
对于问题的划分:两种:一种是严重的问题,一种非严重的问题。
对于严重的,java通过Error类进行描述。对于Error一般不编写针对性的代码对其进行处理。
对于非严重的,java通过Exception类进行描述。对于Exception可以使用针对性的处理方式进行处理。
无论Error或者Exception都具有一些共性内容。比如:不正常情况的信息,引发原因等。
Throwable
|--Error
|--Exception
- 例子:被除数为零。
class Demo0
{
int div(int a,int b)
{
return a/b;
}
}
public class ExceptionDemo {
public static void main(String[] args) {
Demo0 d = new Demo0();
int x = d.div(4,0);
System.out.println("x="+x);
System.out.println("over");
}
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Demo0.div(ExceptionDemo.java:5)
at ExceptionDemo.main(ExceptionDemo.java:11)
异常的处理
java提供了特优的语句进行处理。
try
{
需要被检测的代码
}
catch(异常类 变量)
{
处理异常的代码:(处理方式)
}
finally
{
一定会执行的语句
}
对捕获到的异常对象进行常见方法操作。String getMessage():获取异常信息。
class Demo0 {
int div(int a, int b) {
return a / b;
}
}
public class ExceptionDemo {
public static void main(String[] args) {
Demo0 d = new Demo0();
try {
int x = d.div(4, 0);
System.out.println("x=" + x);
} catch (Exception e)//Exception e = new ArithmeticException();
{
System.out.println("除零啦");
System.out.println(e.getMessage());// /by zero;
System.out.println(e.toString());//异常名称:异常信息。
e.printStackTrace();//异常名称,异常信息,异常出现的位置。//其实jvm默认的异常处理机制,就是在调用printStackTrace方法打印异常的堆栈的跟踪信息。
}
System.out.println("over");
}
}
除零啦
/ by zero
java.lang.ArithmeticException: / by zero
over
java.lang.ArithmeticException: / by zero
at Demo0.div(ExceptionDemo.java:3)
at ExceptionDemo.main(ExceptionDemo.java:11)
class Demo0
{
int div(int a, int b) throws Exception
{
return a / b;
}
}
public class ExceptionDemo {
public static void main(String[] args) {
Demo0 d = new Demo0();
int x = d.div(4, 1);
System.out.println("x=" + x);
System.out.println("over");
}
}
编译失败
Error:(12, 22) java: 未报告的异常错误java.lang.Exception; 必须对其进行捕获或声明以便抛出
class Demo0
{
int div(int a, int b) throws Exception
{
return a / b;
}
}
public class ExceptionDemo {
public static void main(String[] args) throws Exception
{
Demo0 d = new Demo0();
int x = d.div(4, 1);
System.out.println("x=" + x);
System.out.println("over");
}
}
//输出
x=4
over
class Demo0
{
int div(int a, int b) throws Exception
{
return a / b;
}
}
public class ExceptionDemo {
public static void main(String[] args) throws Exception
{
Demo0 d = new Demo0();
int x = d.div(4, 0);
System.out.println("x=" + x);
System.out.println("over");
}
}
//编译失败
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Demo0.div(ExceptionDemo.java:5)
at ExceptionDemo.main(ExceptionDemo.java:13)
class Demo0
{
int div(int a, int b) throws Exception
{
return a / b;
}
}
public class ExceptionDemo {
public static void main(String[] args) throws Exception
{
Demo0 d = new Demo0();
try
{
int x = d.div(4, 0);
System.out.println("x=" + x);
}
catch (Exception e)
{
System.out.println(e.toString());
}
System.out.println("over");
}
}
//输出
java.lang.ArithmeticException: / by zero
over