• java异常


    一、错误

    程序无法处理,写代码时要注意

    二、throw

    public class Test {
        public static void main(String[] args) {
            Test test=new Test();
            test.chufa(3,0);
        }
    
        public void chufa(int a,int b){
            if(b==0){
                throw new ArithmeticException("分母不能是0");
            }
            System.out.println(b/3);
            //执行不到下面这句程序就退出了
            System.out.println("ok");
        }
    }

    RuntimeException类与子类的异常不需要用throws处理,jvm能自动报异常

    子类包括:

    InputMismatchException 输入不匹配异常

    ArithmeticException 算术运算异常

    NullPointerException 空指针异常

    ArrayIndexOutOfBoundsException 数组下标越界异常

    ClassCastException 类型转换异常

    三、throws

    public class Test {
        public static void main(String[] args) throws Exception {
            Test test = new Test();
            test.chufa(6,3);
        }
    
        public void chufa(int a,int b) throws Exception {
            if(b==0){
                throw new Exception("分母不能是0");
            }
            System.out.println(b/3);
            //执行不到下面这句程序就退出了
            System.out.println("ok");
        }
    }

    四、异常

            try {
                
            } 
            catch (Exception e){
                
            }
            finally {
                
            }

    五、自定义异常

    自定义的异常必须继承自Exception或者RuntimeException

    如果继承自Exception表示是编译期异常,需要try或者throws处理

    如果继承自RuntimeException表示是运行期异常,由jvm处理

    定义

    public class CustomException extends  Exception{
    
        public CustomException() {
            super();
        }
    
        public CustomException(String message) {
            super(message);
        }
    }

    使用

    public class Test {
        public static void main(String[] args) throws CustomException {
            Test test = new Test();
            test.a(11);
        }
    
        public void a(int i) throws CustomException {
            if(i>10){
                throw new CustomException("sa");
            }
        }
    }
  • 相关阅读:
    设置文字内容阴影效果
    android TouchEvent解析(2)
    后台运行 程序
    Intent 大全完整版
    URI URL的区别
    Java中List循环遍历的时候删除当前对象(自己)
    HDU 1005
    XML 导入 Sqlite 遇到的强大工具Navicat
    android eclipse开发环境 自动提示 程序无法响应解决方法
    DOM4J 递归解析xml文件
  • 原文地址:https://www.cnblogs.com/buchizaodian/p/13396988.html
Copyright © 2020-2023  润新知