zoukankan      html  css  js  c++  java
  • JAVA 异常

    使用try…catch

    public class Test {
    
        public Test() {
            // TODO Auto-generated constructor stub
        }
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            try {
                System.out.println("try start");
                int i = 1 / 0;
                System.out.println("try end");
            } catch (Exception e) {
                // TODO: handle exception
                System.out.println("catch");
                e.printStackTrace();
            } finally {
                System.out.println("finally");
            }
        }
    
    }

    运行结果

    try start
    catch
    finally
    java.lang.ArithmeticException: / by zero
        at Test.main(Test.java:12)

    运行时异常

    public class Test {
    
        public Test() {
            // TODO Auto-generated constructor stub
        }
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
    
            if (true) {
                RuntimeException e = new RuntimeException("产生异常");
                throw e;
            }
    
        }
    
    }

    运行结果

    Exception in thread "main" java.lang.RuntimeException: 产生异常
        at Test.main(Test.java:12)

    使用throws

    public class Test {
    
        public Test() {
            // TODO Auto-generated constructor stub
        }
    
        public static void main(String[] args) throws Exception {
            // TODO Auto-generated method stub
    
            if (true) {
                Exception e = new Exception("产生异常");
                throw e;
            }
    
        }
    
    }

    运行结果

    Exception in thread "main" java.lang.Exception: 产生异常
        at Test.main(Test.java:12)
  • 相关阅读:
    各种经典透镜投影模型
    表达式和运算
    数组
    如何使用布尔类型
    如何使用数字类型
    如何使用字符串类型
    如何声明变量,如何给变量赋值
    变量 构造函数 New 关键字
    调用write方法打印语句到浏览器
    MVC中几种常用ActionResult
  • 原文地址:https://www.cnblogs.com/zhangxuechao/p/13602646.html
Copyright © 2011-2022 走看看