• 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>

  • 相关阅读:
    【Java】久违了,Hello World!
    【Java】番外——BUG一词的由来
    【Java】数据类型、关键字、标识符
    【Java】一年后,重新开始学习Java!
    【Java】Path环境变量、Java_HOME
    【Java】Java环境安装
    反射
    修改metronome
    python 简单的动漫排名爬虫
    python 打包的 exe 程序自动更新
  • 原文地址:https://www.cnblogs.com/createyuan/p/8157671.html
Copyright © 2020-2023  润新知