1

我想知道是否有一种简单的抛出异常的方法,但只能使用我选择的确切字符串。我找到了一种摆脱堆栈跟踪的方法,但现在我想删除每个异常的开头:

“线程“主”RuntimeException 中的异常......”

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

谢谢!

4

7 回答 7

3

正确的方法是设置您自己的、自定义的、未捕获的异常处理程序:

public static void main(String... argv)
{
  Thread.setDefaultUncaughtExceptionHandler((t, e) -> System.err.println(e.getMessage()));
  throw new IllegalArgumentException("Goodbye, World!");
}
于 2016-01-13T20:36:41.130 回答
1

做就是了:

try {
    ...
} catch (Exception e) {
    System.err.print("what ever");
    System.exit(1); // close the program
}
于 2016-01-13T20:27:56.873 回答
0

您可以通过创建Exception可以自己创建的自定义来做到这一点。

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

根据您所写的内容,您似乎想要一个Unchecked未强制执行但在运行时引发错误的异常。

一种方法是通过以下方式:

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 执行此操作。

于 2016-01-13T20:39:27.770 回答
0

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

于 2016-01-13T20:27:50.700 回答
0

你不能,除非你得到 openJDK,改变源代码并重新编译。

但是,大多数开发人员通常会使用一些日志库,例如 log4j,并根据日志记录设置使用不同的详细信息级别。

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

于 2016-01-13T20:27:51.180 回答
0

这就是你的做法:

try{
   //your code
 }catch(Exception e){
   System.out.println("Whatever you want to print" + e.getMessage());
   System.exit(0);
 } 
于 2016-01-13T20:23:10.047 回答
0

我不确定我是否完全理解您的问题,但是如果您只是将“抛出异常”添加到方法标头并在它应该失败的方法中抛出异常,那应该可以工作。

例子:

public void HelloWorld throws Exception{
    if(//condition that causes failure)
        throw new Exception("Custom Error Message");
    else{
        //other stuff...
    }
}
于 2016-01-13T20:31:45.220 回答