zoukankan      html  css  js  c++  java
  • java异常类的使用

    1.异常的概念

      什么是异常?程序出错分为两部分,编译时出粗和运行时出错。编译时出错是编译器在编译源码时发生的错误;

      运行时出错是在编译通过,在运行时出现的错误。这种情况叫异常。

      例如:数组越界,除数为0,文件找不到等等。

      异常的层次:

      Object

        Throwable

          Error

          Exception

            RuntimeException

            IOException

    2.如何解决异常

      a.使用try...catch

      

    public class UsingTryCatch {
        public static void main(String args[]) {
            int a = 5;
            int b = 0;
            int result = 0;
            try {
                result = a / b;
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    
    }

      b.使用throws或throw关键字

    public class UsingThrows {
        public static void main(String args[]) {
            try {
                Caculation caculation = new Caculation();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        public static class Caculation{
            int a = 5;
            int b = 0;
            int result = 0;
    
            public Caculation()throws Exception{
                result = a/b;
                System.out.println(result);
            }
        }
    }
    public class UsingThrow {public static void main(String args[]) {
        try {
    //        Caculation caculation = new Caculation();
            throw new Exception("实例化Exception");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
        public static class Caculation{
            int a = 5;
            int b = 0;
            int result = 0;
    
            public Caculation()throws Exception{
                result = a/b;
                System.out.println(result);
            }
        }
    }
  • 相关阅读:
    算法竞赛入门经典训练指南——UVA 11300 preading the Wealth
    hiho一下 第148周
    ajax总结及案例
    Spring事务
    Struts2拦截器介绍
    Struts2的拦截器----Dog实例
    Struts2文件的下载
    Struts2文件的上传
    Struts2类型转换
    Struts2 属性驱动、模型驱动、异常机制
  • 原文地址:https://www.cnblogs.com/prescheng/p/5838975.html
Copyright © 2011-2022 走看看