简体   繁体   English

引发异常而没有“线程异常…”

[英]Throwing an exception without “Exception in thread…”

I would like to know if there's a simple way of throwing an exception, but ONLY with the exact string I choose. 我想知道是否有一种简单的引发异常的方法,但是只能使用我选择的确切字符串。 I found a way to get rid of the stack trace, but now I want to remove the beginning of every exception: 我找到了摆脱堆栈跟踪的方法,但是现在我想删除每个异常的开头:

"Exception in thread "main" RuntimeException..." “线程“主”中的异常RuntimeException ...”

I'm looking for a simple, elegant way to do this (not super simple, but not way too complicated as well). 我正在寻找一种简单,优雅的方法来做到这一点(不是超级简单,但也不会太复杂)。

Thanks! 谢谢!

The correct way to do this is to set your own, custom, uncaught exception handler: 正确的方法是设置自己的,自定义的, 未捕获的异常处理程序:

public static void main(String... argv)
{
  Thread.setDefaultUncaughtExceptionHandler((t, e) -> System.err.println(e.getMessage()));
  throw new IllegalArgumentException("Goodbye, World!");
}

Just do: 做就是了:

try {
    ...
} catch (Exception e) {
    System.err.print("what ever");
    System.exit(1); // close the program
}

This is how you do it : 这是您的操作方式:

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

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

You can't, except if you get openJDK, change the sources and recompile. 除了获得openJDK之外,您不能更改源代码并重新编译。

However, what most developers usually do is to use some logging library such as log4j and use different detail levels, according to the logging settings. 但是,大多数开发人员通常会根据日志记录设置使用某些日志记录库(例如log4j)并使用不同的详细程度。

So you can print the full stacktrace using a lower level such as TRACE or DEBUG and a more human-readable message in the ERROR or WARN (or even INFO) levels. 因此,您可以使用较低的级别(例如TRACE或DEBUG)以及在ERROR或WARN(甚至INFO)级别中更易于理解的消息来打印完整的堆栈跟踪。

I'm not sure I understand your question fully, but if you just add "throws Exception" to the method header and throw the exception in the method where it should fail, that should work. 我不确定我是否完全理解您的问题,但是如果您仅将“ throws Exception”添加到方法标头,然后将异常抛出到应该失败的方法中,那应该可以。

Example: 例:

public void HelloWorld throws Exception{
    if(//condition that causes failure)
        throw new Exception("Custom Error Message");
    else{
        //other stuff...
    }
}

You can do this by creating a custom Exception that you can create yourself. 您可以通过创建可以创建自己的自定义Exception来实现。

  • These exceptions can either be Checked exceptions, that are enforced by Java compiler (Requires try/catch or throws to implement) 这些异常可以是Java编译器强制执行的Checked异常(需要try / catch或throws来实现)。
  • Or the exception can be Unchecked exception, which throws during runtime, that are not enforced by the Java compiler. 或者,该异常可以是Java编译器未强制执行的Unchecked异常,该异常在运行时抛出。

Based on what you have written, it seems you want an Unchecked exception that is not enforced, but throws an error during runtime. 根据您所写的内容,您似乎想要一个Unchecked强制执行的Unchecked异常,但在运行时会引发错误。

One way of doing this is through the following: 一种方法是通过以下方法:

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"); 
       }
}

Then in your code, you could do the following: 然后,在您的代码中,您可以执行以下操作:

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

Or 要么

 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);
 }

You can also do this for Throwable as well. 您也可以为Throwable执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM