在java中使用finally块捕获异常及其消息

在java中使用finally块捕获异常及其消息,java,exception-handling,try-catch-finally,Java,Exception Handling,Try Catch Finally,我有以下代码,我喜欢使用finally获取异常消息,因为使用catch可以很容易地通过它的arg获取异常消息。但我知道我无法使用finally获取异常消息 try { MyClass obj=new MyClass(); obj.strProName = jobj1.getString("productname"); obj.strPrice = jobj1.getString("price"); obj.strCurrency = jobj1.getString("currency")

我有以下代码,我喜欢使用finally获取异常消息,因为使用catch可以很容易地通过它的arg获取异常消息。但我知道我无法使用finally获取异常消息

try {
 MyClass obj=new MyClass();
 obj.strProName = jobj1.getString("productname");
 obj.strPrice = jobj1.getString("price");
 obj.strCurrency = jobj1.getString("currency");
 obj.strSalePrice = jobj1.getString("saleprice");
 obj.strStoreName = jobj1.getString("storename");

//arrayList.add(obj);
throw new Exception("Exception Reason!");

}
finally{
 //want to get that exception message here without using catch or can see how finally catching here the exception
}

最后
未捕获异常。只能在
catch
块中捕获异常。
finally
块的目的是在两种情况下都执行,即无论是否发生异常,它都将执行

但据我所知,我无法使用 最后

没错,为了抓住你的机会,嗯。。。必须使用catch子句


但是,您可以将消息存储在变量中(在catch子句中),然后在finally子句中使用该变量。

catch block
不同,
finally
block不会收到任何
异常
实例

所以,我的回答是否定的

我的意思是要打印消息,您需要
Exception
instance

根据文件()

块是大括号内的一系列语句、局部类声明和局部变量声明语句

因此,在catch块
catch(异常e){}
之外,您无法访问它(
e
)。

试试这个

try {
       .....
       throw new Exception("Exception Reason!");
    }
catch(Exception e){
     msg=e.getMessage();
finally{
//USE String msg here.
}

最后,不捕获异常,它只是一个您可以用来始终执行某些操作的东西,即使没有错误并且从不需要捕获

try {
 MyClass obj=new MyClass();
 obj.strProName = jobj1.getString("productname");
 obj.strPrice = jobj1.getString("price");
 obj.strCurrency = jobj1.getString("currency");
 obj.strSalePrice = jobj1.getString("saleprice");
 obj.strStoreName = jobj1.getString("storename");
}
//arrayList.add(obj); here you can Catch the exception, meaning it will only show if there is an exception!
catch(Exception e){
 System.out.print(e+"=Exception Reason!");
}
finally{
//Finally is used to do something no matter what. 
//It will do what ever you want it to do, 
//even if the catch is never used. 
//Use catch to show exception, 
//finally to close possible connections to db etc.
}

@当然,你的一句话抵得上我的三句话:)我知道这一点,但现在我的问题仍然没有答案。因为我只想知道这个东西有多新异常(“消息”)是由finally解析的。因为它们必须是任何一个字符串参数,所以需要调用方法,但catch不存在,但catch是..你能对此提出建议吗?我在问题中也提到了这一点,但我想使用finally而不使用catch获取消息,因为你现在finally是catch的替代品。是的。但使用finally块无法捕获异常。我想您可能希望消息位于finally block中,这就是我建议使用上述选项的原因。我想知道在不使用catch的情况下,Exception类的string arg构造函数是如何由抛出的Exception for case管理的。我只有这种困惑。你能提出一些建议吗?试着调试你的程序。您将了解异常的流程。有一个为
Exception(String msg)
定义的构造函数,它最终会将您的msg保存在
detailMessage
字段中。因为我在代码中抛出一个新的异常(String)对象,所以如果异常(String msg)不可用,则我的代码中会出现编译时错误。此答案在这里没有任何新的内容,因为我在问题中也提到了类似的内容。我想知道如何使用finally而不使用catch获取消息,因为它们必须是任何异常(字符串)cons将被调用,但通过使用,我们没有在代码中提供它。那么我们的代码如何或最终如何做到这一点。我只想知道这件事。你能解释一下这个想法吗