zoukankan      html  css  js  c++  java
  • java学习笔记 异常处理

    1、

    public class ExceptionDemo1 {
        public static void main(String[] args) {
            System.out.println("1、除法计算开始:");
            try {
                int x = 10;
                int y = 0;
                System.out.println("开始计算:"+(x/y));
                System.out.println("除法结束");
            }catch (ArithmeticException e){
                e.printStackTrace();
            }finally {
                System.out.println("不管是否产生异常都执行");
            }
            System.out.println("**********");
        }
    }

    产生异常:

    1、除法计算开始:
    不管是否产生异常都执行
    **********
    java.lang.ArithmeticException: / by zero
        at com.hengqin.test1.ExceptionDemo1.main(ExceptionDemo1.java:9)

    2、异常的处理流程

     3、throws关键字

    class Math{
        //throws表示此方法中存在的异常由调用出处理
        public static int div(int x,int y)throws Exception{
            return x/y;
        }
    }
    public class ThrowsDemo1 {
        public static void main(String[] args) {
            System.out.println(Math.div(10,2));
        }
    }

    报错:

    Error:(10, 36) java: 未报告的异常错误java.lang.Exception; 必须对其进行捕获或声明以便抛出
    class Math{
        //throws表示此方法中存在的异常由调用出处理
        public static int div(int x,int y)throws Exception{
            return x/y;
        }
    }
    public class ThrowsDemo1 {
        public static void main(String[] args) {
            try {
                System.out.println(Math.div(10,2));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    主方法上不要加上throws

    4、throw关键字

    手工抛异常

    public class ThrowDemo1 {
        public static void main(String[] args) {
            try {
                throw new Exception("自己抛的异常");
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    java.lang.Exception: 自己抛的异常
        at com.hengqin.test1.ThrowDemo1.main(ThrowDemo1.java:6)

    5、异常处理标准格式

    class Math{
        //throws表示此方法中存在的异常由调用出处理
        public static int div(int x,int y)throws Exception{
            int result = 0;
            try{
                System.out.println("***计算开始***");
                result = x/y;
            }catch (Exception e){
                throw e;  //继续抛出异常
            }finally {
                System.out.println("***计算结束***");
            }
            return result;
        }
    }
    public class ThrowsDemo1 {
        public static void main(String[] args) {
            try {
                System.out.println(Math.div(10,0));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
  • 相关阅读:
    关于Python对文件字节流数据的处理
    python中的random模块
    软件开发项目验收标准
    pdf文档转图片
    批量处理图片转base64编码
    批量处理图片转为透明色
    python2.7实现本地启一个http服务作为数据转发接收器或模拟接口响应数据源
    系统正常运行指标参考
    Jenkins创建一个自由风格的项目
    KatalonRecorder系列(一):基本使用+XPath元素定位
  • 原文地址:https://www.cnblogs.com/cathycheng/p/13187708.html
Copyright © 2011-2022 走看看