zoukankan      html  css  js  c++  java
  • java_异常处理

    cmd命令行下编译并执行,不过要将package javase8注释掉,否则会报错

    D:codeworkspacemyjavasrcjavase8>java Exception20171231
    错误: 找不到或无法加载主类 Exception20171231

    在命令行下传递参数,divide,null,test,hh

    //package javase8;
    
    class TestException extends Exception {
        TestException(){super();}
        TestException(String s){super(s);}
    }
    
    class Exception20171231 {
    
        public static void main(String[] args) {
            for (String arg : args) {
                try {
                    thrower(arg);
                    System.out.println("Test "" + arg +"" did't throw an exception");
                } catch (Exception e) {
                    System.out.println("Test "" + arg +"" threw a " + e.getClass() + "
        with message: " + e.getMessage());
                }
            }
        }
    
        static int thrower(String s) throws TestException{
            try {
                if (s.equals("divide")) {
                    int i=0;
                    return i/i;
                }
                if (s.equals("null")) {
                    s=null;
                    return s.length();
                }
                if (s.equals("test")) {
                    throw new TestException("Test Message");
                }
                return 0;
            } finally {
                System.out.println("[thrower("" + s +"") done]");
            }
        }
    }

    D:codeworkspacemyjavasrcjavase8>javac Exception20171231.java

    D:codeworkspacemyjavasrcjavase8>java Exception20171231

    D:codeworkspacemyjavasrcjavase8>java Exception20171231 divide
    [thrower("divide") done]
    Test "divide" threw a class java.lang.ArithmeticException
            with message: / by zero

    D:codeworkspacemyjavasrcjavase8>java Exception20171231 null
    [thrower("null") done]
    Test "null" threw a class java.lang.NullPointerException
            with message: null

    D:codeworkspacemyjavasrcjavase8>java Exception20171231 test
    [thrower("test") done]
    Test "test" threw a class TestException
            with message: Test Message

    D:codeworkspacemyjavasrcjavase8>java Exception20171231 hh
    [thrower("hh") done]
    Test "hh" did't throw an exception

    D:codeworkspacemyjavasrcjavase8>

  • 相关阅读:
    【Oracle】修改oracle数据库的字符集
    【OS_Linux】Centos7 设置定时任务
    【 DB_Oracle】Oracle多表关联更新
    Java后端技术路线
    【 OS_Linux】centos下查找jdk的安装路径
    【实用工具】Notepad++的主题和字体设置
    【OS_Linux】Linux删除指定日期之前的文件
    【OS_Windows】windows下删除指定日期前的文件
    C#计算一段程序运行时间的三种方法
    Win10 新功能 改变显示器色彩
  • 原文地址:https://www.cnblogs.com/createyuan/p/8157671.html
Copyright © 2011-2022 走看看