代码之家  ›  专栏  ›  技术社区  ›  edle

在没有“线程中的异常…”的情况下引发异常

  •  1
  • edle  · 技术社区  · 10 年前

    我想知道是否有抛出异常的简单方法,但是 仅限 与我选择的字符串完全相同。我找到了一种摆脱堆栈跟踪的方法,但现在我想删除每个异常的开头:

    线程“main”运行时异常

    我正在寻找一种简单、优雅的方法来做到这一点(不是超级简单,但也不是太复杂)。

    谢谢

    7 回复  |  直到 10 年前
        1
  •  3
  •   erickson    10 年前

    正确的方法是设置自己的自定义, uncaught exception handler:

    public static void main(String... argv)
    {
      Thread.setDefaultUncaughtExceptionHandler((t, e) -> System.err.println(e.getMessage()));
      throw new IllegalArgumentException("Goodbye, World!");
    }
    
        2
  •  1
  •   Dima Maligin    10 年前

    只要做到:

    try {
        ...
    } catch (Exception e) {
        System.err.print("what ever");
        System.exit(1); // close the program
    }
    
        3
  •  0
  •   Pritam Banerjee Ashish Karnavat    10 年前

    这就是你的做法:

    try{
       //your code
     }catch(Exception e){
       System.out.println("Whatever you want to print" + e.getMessage());
       System.exit(0);
     } 
    
        4
  •  0
  •   BritishKnight    10 年前

    构造异常对象时,其中一个构造函数将获取消息的String对象。

        5
  •  0
  •   Leonardo Kenji Shikida    10 年前

    除非得到openJDK,否则不能更改源代码并重新编译。

    然而,大多数开发人员通常会使用一些日志库,如log4j,并根据日志设置使用不同的详细级别。

    因此,您可以使用较低级别(如TRACE或DEBUG)打印完整的堆栈跟踪,并在ERROR或WARN(甚至INFO)级别中打印更易于阅读的消息。

        6
  •  0
  •   Eagle'sNest    10 年前

    我不确定我是否完全理解您的问题,但如果您只是将“throws Exception”添加到方法头中,并在该方法失败的地方抛出异常,这应该会起作用。

    例子:

    public void HelloWorld throws Exception{
        if(//condition that causes failure)
            throw new Exception("Custom Error Message");
        else{
            //other stuff...
        }
    }
    
        7
  •  0
  •   Baleroc    10 年前

    您可以通过创建自定义 Exception 你可以创造自己。

    • 这些异常可以是 Checked 异常,由Java编译器强制执行(需要try/catch或throws来实现)
    • 或者例外可以是 Unchecked 异常,该异常在运行时抛出,Java编译器不强制执行。

    根据你所写的,你似乎想要一个 未选中 未强制执行但在运行时抛出错误的异常。

    一种方法是:

    public class CustomException extends RuntimeException {
           CustomException() {
                  super("Runtime exception: problem is..."); // Throws this error message if no message was specified.
           }
    
           CustomException(String errorMessage) {
                super(errorMessage); // Write your own error message using throw new CustomException("There was a problem. This is a custom error message"); 
           }
    }
    

    然后在代码中,您可以执行以下操作:

    public class Example {
        String name = "x";
        if(name.equals("x"))
              throw new CustomException();   // refers to CustomException()
    }
    

     public class Example2 {
            String name = "y";
            if(name.equals("y")) 
                 throw new CustomException("Error. Your name should not be this letter/word."); // Refers to CustomException(String errorMessage);
     }
    

    你也可以为Throwable这样做。