In my C# application I'm using the following statement:
public void Write(XDocument outputXml, string outputFilename) {
outputXml.Save(outputFilename);
}
How can I find out which exceptions the Save method might throw? Preferably right in Visual Studio 2012 or alternatively in the MSDN documentation.
XDocument.Save does not give any references. It does for other methods, e.g. File.IO.Open.
Unfortunately MSDN do not have any information about exceptions thrown by XDocument and many other types from System.Xml.Linq namespace.
But here is how saving implemented:
public void Save(string fileName, SaveOptions options)
{
XmlWriterSettings xmlWriterSettings = XNode.GetXmlWriterSettings(options);
if ((declaration != null) && !string.IsNullOrEmpty(declaration.Encoding))
{
try
{
xmlWriterSettings.Encoding =
Encoding.GetEncoding(declaration.Encoding);
}
catch (ArgumentException)
{
}
}
using (XmlWriter writer = XmlWriter.Create(fileName, xmlWriterSettings))
Save(writer);
}
If you will dig deeper, you'll see that there is large number of possible exceptions. E.g. XmlWriter.Create method can throw ArgumentNullException. Then it creates XmlWriter which involves FileStream creation. And here you can catch ArgumentException, NotSupportedException, DirectoryNotFoundException, SecurityException, PathTooLongException etc.
So, I think you should not try to catch all this stuff. Consider to wrap any exception in application specific exception, and throw it to higher levels of your application:
public void Write(XDocument outputXml, string outputFilename)
{
try
{
outputXml.Save(outputFilename);
}
catch(Exception e)
{
throw new ReportCreationException(e); // your exception type here
}
}
Calling code can catch only ReportCreationException and log it, notify user, etc.
If the MSDN doesn't state any I guess that Class won't throw any exception. Although, I don't think that this object will be responsible for writing the actual file to disk. So you might receive exceptions from other classes used by XDocument.Save();
To be on the safe side, I would trap all exceptions and try out some obvious erratic instructions, see below.
try
{
outputXml.Save("Z:\\path_that_dont_exist\\filename");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Here, catching Exception will catch any types of exceptions.
Related
This may be a basic question but I have not been able to find an answer from searching. I have code that is causing an exception to be written to the Output -> Debug window in Visual Studio. My try...catch is proceeding to the next line of code anyway. The exception is with a NuGet package.
Does this mean an exception is happening in the NuGet package and is handled by the Nuget package? How can I troubleshoot this further?
private void HandleStorageWriteAvailable(IXDocument doc)
{
using IStorage storage = doc.OpenStorage(StorageName, AccessType_e.Write);
{
Debug.WriteLine("Attempting to write to storage.");
try
{
using (Stream str = storage.TryOpenStream(EntityStreamName, true))
{
if (str is not null)
{
try
{
string test = string.Concat(Enumerable.Repeat("*", 100000));
var xmlSer = new XmlSerializer(typeof(string));
xmlSer.Serialize(str, test);
}
catch (Exception ex)
{
Debug.WriteLine("Something bad happened when trying to write to the SW file.");
Debug.WriteLine(ex);
}
}
else
{
Debug.WriteLine($"Failed to open stream {EntityStreamName} to write to.");
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
}
The exception happens on the line using (Stream str = storage.TryOpenStream(EntityStreamName, true)) when the exception happens the code proceeds to the next line not the catch.
Is this normal behaviour if that exception is being handled by something else? I've never seen this before.
In general, a method called TrySomething will be designed so that it won't throw an exception, but return some sort of error code instead.
Check for example the Dictionary class : it has an Add method which can throw an ArgumentException if the key already exists, and a TryAdd method which instead just returns false.
Chances are, your IStorage implementation of TryOpenStream also has an OpenStream method, and the Try version is just a try/catch wrapper which outputs the error to the Console in case of error.
How do you know it happens on that line?
However there is a setting that enables breaking handled exception in "Exception Settings" dialog (Ctrl+Alt+E). For each type of exception you can control. Here is a link that explain how it works : https://learn.microsoft.com/en-us/visualstudio/debugger/managing-exceptions-with-the-debugger?view=vs-2022
I want to write a String to a Unicode file. My code in Java is:
public static boolean saveStringToFile(String fileName, String text) {
BufferedWriter out = null;
boolean result = true;
try {
File f = new File(fileName);
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(f), "UTF-8"));
out.write(text);
out.flush();
} catch (Exception ex) {
result = false;
} finally {
if (out != null)
try {
out.close();
} catch (IOException e) {
// nothing to do! couldn't close
}
}
return result;
}
Update
Now compare it to C#:
private static bool SaveStringToFile(string fileName, string text)
{
using (StreamWriter writer = new StreamWriter(fileName))
{
writer.Write(text);
}
}
or even try..catch form would be:
private static bool SaveStringToFile(string fileName, string text)
{
StreamWriter writer = new StreamWriter(fileName);
try
{
writer.Write(text);
}catch (Exception ex)
{
return false;
}
finally
{
if (writer != null)
writer.Dispose();
}
}
Maybe it's because I'm from the C# and .Net world. But is this the right way to write a String to a file? It's just too much code for such simple task. In C#, I would say to just out.close(); and that was it but it seems a bit strange to add a try..catch inside a finally statement. I added the finally statement to close the file (resource) no matter what happens. To avoid using too much resource. Is this the right way in Java? If so, why close throws exception?
You are correct in that you need to call the close() in the finally block and you also need to wrap this is a try/catch
Generally you will write a utility method in you project or use a utility method from a library like http://commons.apache.org/io/apidocs/org/apache/commons/io/IOUtils.html#closeQuietly(java.io.Closeable) to closeQuietly .i.e. ignore any throw exception from the close().
On an additional note Java 7 has added support for try with resources which removes the need to manually close the resouce - http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Yes, There is nothing strange about Try catch inside finally() in java. close() may throw IoException for various reasons, thats why it has to enclosed by try catch blocks. There is an improved solution to this problem of yours, in the latest java SE 7 Try with resources
The Java equivalent to the using statement is the try-with-resources statement added in Java 7:
public static void saveStringToFile(String fileName, String text) throws IOException {
try (Writer w = new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8")) {
w.write(text);
}
}
The try-with-resources will automatically close the stream (which implicity flushes it), and throw any exceptions encountered when doing so.
A BufferedWriter is not necessary if you do a single call to write anyway (its purpose is to combine several writes to the underlying stream to reduce the number of system calls, thereby improving performance).
If you insist on handling errors by returning false, you can add a catch clause:
public static boolean saveStringToFile(String fileName, String text) {
try (Writer w = new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8")) {
w.write(text);
return true;
} catch (IOException e) {
return false;
}
}
This should do the trick. If you want to manage exception with complex behavior - then create StreamWriter
public static bool saveStringToFile(String fileName, String text)
{
try
{
File.WriteAllText(fileName, text, Encoding.UTF8);
}
catch (IOException exp)
{
return false;
}
return true;
}
So, what is the question? There is no right or wrong way. Can close even throw an IO Exception ? What do you do then? I generally like non rethrowing of any sort not at all.
The problem is - you just swallow an IO Exception on Close - good. CAN you live with that blowing? If not you have a problem, if yes - nothing wrong.
I never did that, but - again, that depends on your business case.
arch = new File("path + name");
arch.createNewFile();
FileOutputStream fos = new FileOutputStream(arch);
fos.write("ur text");
fos.close();
my way.
The best way to avoid that is putting your out.close() after out.flush() and the process is automatically handled if the close fails. Or use this is better (what I am using) :
File file = ...
OutputStream out = null;
try {
out = new BufferedOutputStream(new FileOutputStream(file));
...
finally {
if (out != null) {
out.close();
}
}
}
If you want a minimum of code you can use FileUtils.writeStringToFile
FileUtils.writeStringToFile(new File(fileName), text);
and I wouldn't use boolean as it rarely a good idea to ignore either the fact an error occured or the reason it occured which is in the message of the exception. Using a checked Exception ensures the caller will always deal with such error correctly and can log meaningful error messages as to why.
To save the file using a specific CharSet
try {
FileUtils.writeStringToFile(new File(fileName), text, "UTF-8");
} catch(IOException ioe) {
Logger.getLogger(getClass()).log(Level.WARNING, "Failed to write to " + fileName, ioe);
}
What are the possible exceptions that can be thrown when XDocument.Load(XmlReader) is called? It is hard to follow best practices (i.e. avoiding generic try catch blocks) when the documentation fails to provide crucial information.
Thanks in advance for your assistance.
MSDN says: The loading functionality of LINQ to XML is built upon XmlReader.Therefore, you might catch any exceptions that are thrown by the XmlReader. Create overload methods and the XmlReader methods that read and parse the document.
http://msdn.microsoft.com/en-us/library/756wd7zs.aspx
ArgumentNullException and SecurityException
EDIT: MSDN not always says true. So I've analyzed Load method code with reflector and got results like this:
public static XDocument Load(XmlReader reader)
{
return Load(reader, LoadOptions.None);
}
Method Load is calling method:
public static XDocument Load(XmlReader reader, LoadOptions options)
{
if (reader == null)
{
throw new ArgumentNullException("reader"); //ArgumentNullException
}
if (reader.ReadState == ReadState.Initial)
{
reader.Read();// Could throw XmlException according to MSDN
}
XDocument document = new XDocument();
if ((options & LoadOptions.SetBaseUri) != LoadOptions.None)
{
string baseURI = reader.BaseURI;
if ((baseURI != null) && (baseURI.Length != 0))
{
document.SetBaseUri(baseURI);
}
}
if ((options & LoadOptions.SetLineInfo) != LoadOptions.None)
{
IXmlLineInfo info = reader as IXmlLineInfo;
if ((info != null) && info.HasLineInfo())
{
document.SetLineInfo(info.LineNumber, info.LinePosition);
}
}
if (reader.NodeType == XmlNodeType.XmlDeclaration)
{
document.Declaration = new XDeclaration(reader);
}
document.ReadContentFrom(reader, options); // InvalidOperationException
if (!reader.EOF)
{
throw new InvalidOperationException(Res.GetString("InvalidOperation_ExpectedEndOfFile")); // InvalidOperationException
}
if (document.Root == null)
{
throw new InvalidOperationException(Res.GetString("InvalidOperation_MissingRoot")); // InvalidOperationException
}
return document;
}
Lines with exceptions possibility are commented
We could get the next exceptions:ArgumentNullException, XmlException and InvalidOperationException.
MSDN says that you could get SecurityException, but perhaps you can get this type of exception while creating XmlReader.
XmlReader.Create(Stream) allows two types of exceptions: [src]
XmlReader reader; // Do whatever you want
try
{
XDocument.Load(reader);
}
catch (ArgumentNullException)
{
// The input value is null.
}
catch (SecurityException)
{
// The XmlReader does not have sufficient permissions
// to access the location of the XML data.
}
catch (FileNotFoundException)
{
// The underlying file of the path cannot be found
}
Looks like the online documentation doesn't state which exceptions it throws... too bad.
You will save yourself some grief with FileNotFoundException's by using a FileInfo instance, and calling its Exists method to make sure the file really is there. That way you won't have to catch that type of exception.
[Edit]
Upon re-reading your post, I forgot to notice that you are passing in an XML Reader. My response was based upon passing in a string that represents a file (overloaded method).
In light of that, I would (like the other person who responded to your question had a good answer too).
In light of the missing exception list, I would suggest to make a test file with malformed XML and try loading it to see what type of exceptions really do get thrown. Then handle those cases.
I was following a tutorial about web scraping in .NET 6 using XDocument. However, when I called XDocument.Load("...") to load an .html page, I got the following exception:
System.Xml.XmlException: ''src' is an unexpected token. The expected token is '='. Line 47, position 32.'
So depending on what you will parse, and if you need something more permissive, perhaps another library is more suited. I went with IronWebScraper, which works better for the HTML I am working with.
How can I handle an expected exception?
I have code in my MVC controller that calls the following:
u.RowKey == new SimplerAES().Dec(HttpServerUtility.UrlTokenDecode(id)));
In my other SimplerAES class:
public string Dec(byte[] encrypted)
{
return encoder.GetString(Decrypt(encrypted));
}
public byte[] Decrypt(byte[] buffer)
{
try {
MemoryStream decryptStream = new MemoryStream();
using (CryptoStream cs = new CryptoStream(decryptStream, decryptor, CryptoStreamMode.Write))
{
cs.Write(buffer, 0, buffer.Length);
}
return decryptStream.ToArray();
} catch(CryptographicException e){
//... do something with it ...
return null; // I put the return null here as I got a syntax message saying
// not all code returns
}
}
Can someone please explain how I get the message that decrypt failed all the way up
to the point where I first try to get the RowKey. Do I have to put u.RowKey within
a try catch as well?
Just don't catch the exception in your method, unless you really need the "do something" part. If you don't catch the exception, it will bubble up the stack until there's code which does catch it.
If you do need to do something within that method, such as logging, you can catch the exception and rethrow it within your catch block using
throw;
Note that this is preferred over
throw e;
as the latter will rewrite the stack trace. It probably won't make much difference in this particular case, but it's worth being aware of.
I suggest you ignore cryptography for the moment, and go hunting for good articles or books on exception handling in C#. This MSDN page is probably a good starting point.
Assuming that you actually need to do something at this level, simply rethrow the exception:
catch (CrypotgraphicException e)
{
// Do something
throw;
}
However, it might be simpler not to catch it at all and let it bubble up higher to your other exception handler.
If you want to continue having the exception unwind the stack don't return null from the catch block. you need to throw (without the exception reference) to continue unwinding with the same exception.
e.g.
try
{
// Do stuff
}
catch(CryptographicException e)
{
// Do stuff to clean up
throw;
}
If you throw e (which has the existing exception object) you destroy some of the stack trace data which makes it less useful. If you want to add more information, wrap the existing exception in a new exception (as the InnerException) and then throw the new exception object. That way you preserve the full exception information.
try
{
// Do stuff
}
catch(CryptographicException e)
{
// Do stuff to clean up
Exception newEx = new Exception("Some further message", e);
throw newEx;
}
Note: Don't simply create the base Exception object, you should derive a new exception class from an existing base (if a suitable Exception class is not available) and use the derived version. This makes catching much easier because you can then catch the exact type you need and not have to have your catch block figure out what do do because you are throwing overly broad exceptions.
Only ever catch an exception if there is something useful you can do with it. Simply swallowing it an returning null in your Decrypt method is not useful. Instead, let the exception bubble up until it gets to a point where it can be usefully handled..
Do I have to put u.RowKey within a try
catch as well?
This would be a more appropriate place to catch the exception...
following is a code snippet:
class xxx
{
public xxx(){}
try
{
throw new Exception(InvalidoperationException);
}
catch(Exception x)
{
}
catch(InvalidoperationException x)
{
}
}
can anyone tell which exception will raise here and what is the reason behind it.
Wow, lots of problems here. Where to start?
That code won't compile. The try-catch block that you've defined is outside of any method, which is not allowed. You need to move it inside of a method.
Never throw a method that you intend to catch yourself later in the method. That's commonly known as using exceptions for "flow control", which is roundly discouraged. There is a performance cost associated with doing so, and it also makes it very confusing to monitor the exceptions that are being thrown when using a debugger when you have code that's throwing and catching it's own exceptions. Use boolean variables (known as flags) for flow control, if necessary.
Always catch the most derived exception class first. That means you should catch InvalidOperationException first, before trying to catch Exception. You need to reverse the order of your catch blocks in the code that you have.
You should practically never catch System.Exception. The only exceptions that you should catch are those that you explicitly understand and are going to be able to handle. There's virtually no way that you're going to know what went wrong or how to handle it when the only information you have is that a generic exception was thrown.
Along those same lines, you also should never throw this exception from your own code. Choose a more descriptive exception class that inherits from the base System.Exception class, or create your own by inheriting from the same.
I see that other answers are showing you sample code of what your code should look like, were it to be rewritten. I'm not going to do that because if I rewrote your code to be correct, I'd end up with this:
class Xxx
{
public Xxx()
{
}
}
Not particularly helpful.
If the code is like this
class xxx
{
public xxx(){
try
{
throw new Exception(InvalidoperationException);
}
catch(InvalidoperationException x)
{
}
catch(Exception x)
{
}
}
}
It should compile and raise your exception and catch. Otherwise your code will not compile at all.
No exception will be thrown as this code will not even compile.
Regardless - several points:
When using exception handling, put the more specific exception before the less specific ones (so the catch of InvalidOperationException should be before the one for Exception).
Catching Exception is normally no very useful.
If you catch an exception, do something with it.
You probably meant:
throw new InvalidOperationException();
However, the way you structured your exceptions, the catch(Exception x) block would have run.
You should write:
class xxx
{
public void Test()
{
try
{
throw new InvalidoperationException();
}
catch(InvalidoperationException exception)
{
// Do smth with exception;
}
catch(Exception exception)
{
throw; // Rethrows your exception;
}
}
}
InvalidOperationException inherits from Exception.
catch tries to processes the most specific branch, so catch (InvalidOperationException x) will be executed here.
Nope. It wouldn't compile. So, it there's no question about as to which exception will be generated.
Your code should be something like this :
class xxx
{
public void Test()
{
try
{
throw new InvalidoperationException();
}
catch(InvalidoperationException exception)
{
// Something about InvalidOperationException;
}
catch(Exception exception)
{
// Something about the Exception
}
}
}
Point to be noted :
Write more specific class of Exception first, hence we write InvalidOperationException prior to Exception class.
Ignoring the compile issue.... the first matching exception block (catch(Exception x)) will get the exception. You then ignore the exception and don't re-throw, so exception will be seen by the outside world. That doesn't make it good practice, though... in particular, catching an arbitrary Exception and ignoring it is risky - it could have been anything... it isn't necessarily the exception you thought it was.
Well, the code won't compile, but I'll just ignore that...
If I'll just look at the line:
throw new Exception(InvalidoperationException);
1st of all, according to MSDN there is no such constructor. So I will assume you meant the constructor: Exception(String msg, Exception innerException). Meaning:
throw new Exception("blabla", InvalidoperationException);
The exception that is being thrown is of type Exception and not InvalidOperationException. So ONLY catch(Exception x) can catch it.
If you would've thrown InvalidoperationException than the way you wrote the order of the catches, the Exception class would get caught first.
The order of the catches does matter.
The best advice I can give you is simply try it yourself and see what happens.