Java 无论如何,从try块在catch块中执行后续操作
如果xml文件格式不正确,我需要将其保存在目录中。 只是为了分析失败的原因 如何将xml请求保存在catch块的目录中 我试着这么做..但是在try块中创建的变量在catch块中似乎没有定义。我是一个新手…如果这是一个基本的问题,很抱歉。有什么解决办法吗Java 无论如何,从try块在catch块中执行后续操作,java,exception-handling,scope,Java,Exception Handling,Scope,如果xml文件格式不正确,我需要将其保存在目录中。 只是为了分析失败的原因 如何将xml请求保存在catch块的目录中 我试着这么做..但是在try块中创建的变量在catch块中似乎没有定义。我是一个新手…如果这是一个基本的问题,很抱歉。有什么解决办法吗 try { Create a well formed xml request open a http connection and post it } //catching all exceptions here ca
try {
Create a well formed xml request
open a http connection and post it
}
//catching all exceptions here
catch (Exception e) {
e.printStackTrace();
}
{}大括号是try块内的变量,因此在该范围外它们不可用。你可以这样做:
String xml = null;
try {
xml = ...; //Create a well formed xml request
//open a http connection and post it
} catch (Exception e) {
if (xml != null) {
// write XML to file
}
}
如果在try块外部/之前定义变量,则可以在catch内部使用它。实际上,您应该考虑为什么使用Test/catch错误处理作为流控制。 < P>您必须在Tror块之外声明变量,然后它将工作
XmlDocument xml = null;
try {
xml = Create a well formed xml request
open a http connection and post it
}
catch (Exception e) {
xml.save();
}
正如您所说,在try块中声明的任何变量在catch块中都不可用,因此您必须将其放置在内部块中的外部如果您在内部块中创建新元素,则无法从内部块中访问它 所以,若你们在try块中创建了一些东西,那个么它就在上面可见。你无法从街区外够到它 所以,对于您的问题,您应该在try块之外创建xml请求。 像这样的东西
Create a well formed xml request
try {
open a http connection and post it
}
//catching all exceptions here
catch (Exception e) {
e.printStackTrace();
}
try catch finally
,但finally
块应保留用于资源管理