Reputation: 41
I have a need to save a xml file in a directory .....if it is not well formed. Just to analyze it for the reason for the failure.
How do i save the xml request in a directory in catch block?
i tried doing it..but the variables created in the try block seems undefined in catch block. I am a newbie...sorry if its a basic question. any solutions?
try {
Create a well formed xml request
open a http connection and post it
}
//catching all exceptions here
catch (Exception e) {
e.printStackTrace();
}
Upvotes: 2
Views: 426
Reputation: 752
if you create a new element in an inner block it is unreachable out of it.
So if you create something in try block it is just visible on it. You cannot reach that out of the block.
So for your problem you should create xml request out of try block. Something like this;
Create a well formed xml request
try {
open a http connection and post it
}
//catching all exceptions here
catch (Exception e) {
e.printStackTrace();
}
Upvotes: 0
Reputation: 314
You have to declare the variable outside of the try block, then it would work
XmlDocument xml = null;
try {
xml = Create a well formed xml request
open a http connection and post it
}
catch (Exception e) {
xml.save();
}
As you said, any variable declared inside the try block is not available in the catch block, so you have to place it outside
Upvotes: 0
Reputation: 1623
If you define your variable outside/before the try block, you can use it inside the catch. Really though, you should consider why you are using try/catch error handling as flow control.
Upvotes: 0
Reputation: 6901
The {} braces are scoping the variables that are inside your try block, so they're not available outside of that scope. You could do something like this:
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
}
}
Upvotes: 3