我想知道是否有抛出异常的简单方法,但只有只有与我选择的确切字符串。我发现了一个办法摆脱的堆栈跟踪,但现在我想删除每个异常的开头:抛出异常,没有“Exception in thread ...”
“异常线程‘main’的RuntimeException ......”
我正在寻找一个简单,优雅的方式来做到这一点(不是很简单,但也不太复杂)。
谢谢!
我想知道是否有抛出异常的简单方法,但只有只有与我选择的确切字符串。我发现了一个办法摆脱的堆栈跟踪,但现在我想删除每个异常的开头:抛出异常,没有“Exception in thread ...”
“异常线程‘main’的RuntimeException ......”
我正在寻找一个简单,优雅的方式来做到这一点(不是很简单,但也不太复杂)。
谢谢!
做,这是设置你自己的自定义正确的方法,uncaught exception handler:
public static void main(String... argv)
{
Thread.setDefaultUncaughtExceptionHandler((t, e) -> System.err.println(e.getMessage()));
throw new IllegalArgumentException("Goodbye, World!");
}
不会抛出新的IllegalArgumentException(“再见,世界!”);'打印'线程中的异常......'哪几乎是正确的方式,虽然你100%正确的。 –
@DimaMaligin试试看吧 – erickson
你是对的!(+1),从来没有注意到它之前... –
这是你如何做到这一点:
try{
//your code
}catch(Exception e){
System.out.println("Whatever you want to print" + e.getMessage());
System.exit(0);
}
这是一个简单的打印输出...我想通过抛出异常来停止程序。 – edle
就像在catch子句中添加System.exit一样? –
当你构建一个异常对象,一个构造函数将采取消息的String对象。
你不能,除非你得到openJDK,改变源代码并重新编译。
但是,根据日志记录设置,大多数开发人员通常会使用某些日志记录库(如log4j)并使用不同的详细级别。
因此,您可以使用较低级别(例如TRACE或DEBUG)打印完整的堆栈跟踪,并在ERROR或WARN(甚至INFO)级别中输出更易于理解的消息。
只要做到:
try {
...
} catch (Exception e) {
System.err.print("what ever");
System.exit(1); // close the program
}
为什么我忘了System.err.print()? :(谢谢! – edle
@edle欢迎你接受答案,如果它回答你的问题... –
我不知道我完全理解你的问题,但如果你只需要添加“抛出异常”的方法,头和抛出异常的地方应该失败的方法,这应该工作。
例子:
public void HelloWorld throws Exception{
if(//condition that causes failure)
throw new Exception("Custom Error Message");
else{
//other stuff...
}
}
您可以通过创建自定义Exception
,你可以创建自己做到这一点。
Checked
异常,由Java编译器执行(要求的try/catch或抛出来实现)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做这个。
这是非常基本的异常处理...我试图避免堆栈跟踪和每个异常文本的开始。 – edle
这是否有特别的原因? – Kayaman
嗯......对我来说似乎有点多余,因为你要求的只是'try {...} catch(Exception e){System.err.print(“what ever”);}' –
没有特别的原因,我只是想知道这样的事情是否可能以及如何。 – edle