Java 获取异常实例类名
我想知道在这种情况下例外情况是什么:Java 获取异常实例类名,java,exception,Java,Exception,我想知道在这种情况下例外情况是什么: try { // some risky actions } catch (Exception e) { System.out.println("Get instance name there"); } 我怎样才能做到这一点呢?给你: 试试看{ 抛出新的算术异常(); }捕获(例外e){ System.out.println(e.getClass().getCanonicalName()); } 输出: java.lang.Arithmet
try {
// some risky actions
} catch (Exception e) {
System.out.println("Get instance name there");
}
我怎样才能做到这一点呢?给你:
试试看{
抛出新的算术异常();
}捕获(例外e){
System.out.println(e.getClass().getCanonicalName());
}
输出:
java.lang.ArithmeticException
默认异常日志记录类似于
try
{
//
}
catch (Exception e)
{
e.printStackTrace();
}
这会将异常的堆栈跟踪打印到系统。err异常类型显示为以下输出的一部分:
e.printStackTrace();
要以编程方式获取它,可以使用:
String exceptionClassName = e.getClass().getName();
在catch块中,根据异常子类型使用逻辑是一种糟糕的形式。Sonar会将此标记为违反代码()
相反,您应该添加多个catch块来捕获不同类型的异常:
try {
// some risky actions
} catch (java.io.IOException e) {
e.printStackTrace();
}
catch (java.lang.IllegalArgumentException e) {
e.printStackTrace();
}
由于Java 7,您还可以执行以下操作:
多catch的好处是,您可以在一个catch块中处理多个异常类型,而不必还原到一个普通的超类(如
java.lang.exception
),该类将包含大量您不想处理的异常类型。如果您希望添加一些上下文信息,您可以查看
public static void main(String[] args) {
try {
doSomething();
} catch (ContextedRuntimeException e) {
System.out.println(e.getMessage());
System.out.println(e.getContextEntries());
}
}
private static void doSomething() {
int divisor = 0;
int dividend = 100;
int result;
try {
result = dividend / divisor; // Just throw an exception to test things....
System.out.print("DIVISION RESULT: "+result);
} catch (ArithmeticException e) {
throw new ContextedRuntimeException("Oops..division by zero not allowed", e)
.addContextValue("Divisor", divisor)
.addContextValue("Dividend", dividend);
}
}
将输出:
Oops..division by zero not allowed
Exception Context:
[1:Divisor=0]
[2:Dividend=100]
---------------------------------
[(Divisor,0), (Dividend,100)]
e.getClass()
?或者您所说的情况和实例名称是什么意思?您是在询问异常类名称吗?然后调用e.getClass().getSimpleName()
。
Oops..division by zero not allowed
Exception Context:
[1:Divisor=0]
[2:Dividend=100]
---------------------------------
[(Divisor,0), (Dividend,100)]