栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java基础学习14

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java基础学习14

异常处理

程序员查错网站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:UsersLenovoAppDataRoamingTyporatypora-user-imagesimage-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:UsersLenovoAppDataRoamingTyporatypora-user-imagesimage-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:UsersLenovoAppDataRoamingTyporatypora-user-imagesimage-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(“错误的相加操作!”);
}
}
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/287954.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号