异常

作者: wustzhy | 来源:发表于2020-05-14 21:41 被阅读0次

异常

中断了正常指令流的事件;

示例代码

int i = 1/0;
System.out.println(i);

错误日志

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at kkb_006_factoryMethodPattern.Test.main(Test.java:22)

注意

  • 语法上是正确的,编译能通过,发生在运行过程中。
  • 异常发生后,发生地后面的代码不会再执行

执行过程中发生异常时,虚拟机会生成一个异常对象。

异常对象

Throwable
  |- exception
    |-RuntimeException(uncheck exception)
    |-IOException(check exception)
  |- error

上方示例错误日志ArithmeticExceptionRuntimeException的子类

try catch

System.out.println(1);
try {
    int i = 1/0;
    System.out.println(1.5);
} catch (Exception e) { //发生异常则执行
    // TODO: handle exception
    System.out.println(2);
    e.printStackTrace();
}finally {
    System.out.println(3); //一定执行
}
System.out.println(4);

结果

1
2
java.lang.ArithmeticException: / by zero
    at kkb_006_factoryMethodPattern.Test.main(Test.java:24)
3
4

主动抛异常

public class User {

    private int age;
    
    public void setAge(int age) {
        
        if (age < 0) {
            RuntimeException exception = new RuntimeException();
            throw exception; //throw, 抛出异常
        }
        
        this.age = age;
    }
    
    public User() {
        // TODO Auto-generated constructor stub
    }

}

不可使用 Exception exception = new Exception();,否则编译无法通过,报错信息 如下图。

Unresolved compilation problem: 
    Unhandled exception type Exception

因为,Exception属于check exception,编译阶段检查到这样的exception,会无法通过。错误提示如下图

错误提示.png
提示需要这样处理
  1. Add throws declaration (添加异常/抛出声明)
    注意区分:throws, 是用来声明异常。而throw是用来抛出异常。
    在函数内处理,声明异常 代码

    public void setAge(int age) throws Exception{
        
        if (age < 0) {
            Exception exception = new Exception();
            throw exception;
        }
        
        this.age = age;
    }
    
  2. Surround with try/catch (使用try/catch包围)
    在函数被调用的地方处理 ,使用try/catch 代码

        User user = new User();
        try {
            user.setAge(-22);
        } catch (Exception e) {
            // TODO: handle exception
        }
    

异常处理,是java开发中比较体现功力的地方,需要根据经验去判断 是否需要处理、使用上面哪一种处理

相关文章

  • 异常和模块

    异常 目标 了解异常 捕获异常 异常的else 异常finally 异常的传递 自定义异常 一. 了解异常 当检测...

  • python多线程

    异常基础知识 -异常简介: 运行时错误 -异常类: 异常数据 异常名称,异常数据,异常类型 -自定义异常 clas...

  • dart 异常

    dart中的异常 异常处理 抛出异常 异常捕获

  • Java基础之异常

    Java基础之异常 目录 异常简单介绍 ThrowableErrorException 异常分类 如何处理异常异常...

  • python核心编程-错误与异常

    本章主题:什么是异常Python中的异常探测和处理异常上下文管理引发异常断言标准异常创建异常相关模块 什么是异常 ...

  • motan(RPC)系统梳理知识点

    异常分类: 业务异常(bizException) 服务异常(serviceException) 框架异常(fram...

  • 异常

    Java异常体系 异常的分类 Java的异常分为两大类:Checked异常和Runtime异常(运行时异常)。所有...

  • 从零构架个人博客网站(二)-全局异常处理

    中间件的异常 全局异常中间件全局异常监听定义异常的返回结果定义常见的异常状态开发环境 异常查看 对于异常,我们可以...

  • Node.js异常处理

    Node.js异常分类: 变量异常 函数异常 调用异常 变量异常 未定义变量 未包含对象 变量类型错误 函数异常 ...

  • python 异常

    异常 目标 异常的概念 捕获异常 异常的传递 抛出异常 01. 异常的概念 程序在运行时,如果 Python 解释...

网友评论

      本文标题:异常

      本文链接:https://www.haomeiwen.com/subject/huranhtx.html