Java基础学习14

本文介绍了Java中的异常处理机制,包括try-catch-finally语句块的使用,ArithmeticException的捕获,以及自定义异常的创建和抛出。通过示例代码展示了如何在程序中有效地处理和报告错误。
摘要由CSDN通过智能技术生成

异常处理

程序员查错网站http://stackoverflow.com/

程序异常处理关键字:try、catch、finally、throw、throws

1、异常的处理流程;

2、异常的处理格式;

3、异常处理的模型。

//程序异常
public class Day14 {
    public static void main(String[] args) {
        System.out.println("开始");
        try {
            System.out.println("运行"+(10/0));
        }catch (ArithmeticException e){
         e.printStackTrace();
        }
        System.out.println("结束");
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ClYbTZuG-1633234291620)(C:\Users\Lenovo\AppData\Roaming\Typora\typora-user-images\image-20210925115311307.png)]

//程序异常
public class Day14 {
    public static void main(String[] args) {
        System.out.println("开始");
        try {
            System.out.println("运行"+(10/0));
        }catch (ArithmeticException e){
         e.printStackTrace();
        }finally {
            System.out.println("finally");
        }
        System.out.println("结束");
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uLGuixe2-1633234291621)(C:\Users\Lenovo\AppData\Roaming\Typora\typora-user-images\image-20210925115424338.png)]

class MyMath{
    //此处明确告诉用户该方法上会有异常
    public static int div(int x,int y)throws Exception{
        return x/y;
    }
}
public class Test21 {
    public static void main(String[] args) {
        try {
            System.out.println(MyMath.div(10,0));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5XMPk6ox-1633234291622)(C:\Users\Lenovo\AppData\Roaming\Typora\typora-user-images\image-20210925122123642.png)]

//程序员查错网站http://stackoverflow.com/
//自定义错误
class AddException extends Exception{
    public AddException(String msg){
        super(msg);
    }
}
public class Test23 {
    public static void main(String[] args) throws Exception{
        if ((10+20) == 30){
            throw new AddException("错误的相加操作!");
        }
    }
}

== 30){
throw new AddException(“错误的相加操作!”);
}
}
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值