Check if file exist with Try/Catch - c#

I'm new to this about Try/Catch. In the code below I have a simple test to check if a file exist. In my task for my C# lesson I must use Try/Catch, and I'm not sure how to use this, should I still use the if statement inside the Try part or is there a better way to do the checking if a file exist inside Try? Is there any difference if the file is a simple txt file or a serialized file?
if (File.Exists("TextFile1.txt"))
{
MessageBox.Show("The file don't exist!", "Problems!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
The Try/Catch way I must use
try
{
code to check if file exist here
}
catch
{
error message here
}

try
{
if (!File.Exists("TextFile1.txt"))
throw new FileNotFoundException();
}
catch(FileNotFoundException e)
{
// your message here.
}

Try this :
try
{
if(!File.Exist("FilePath"))
throw new FileNotFoundException();
//The reste of the code
}
catch (FileNotFoundException)
{
MessageBox.Show("The file is not found in the specified location");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

If you want to check if the file exists without using File.Exist, then you may try opening the file in a try block, and then catching the exception FileNotFoundException.
try
{
// Read in non-existent file.
using (StreamReader reader = new StreamReader("TextFile1.txt"))
{
reader.Read();
}
}
catch (FileNotFoundException ex)
{
MessageBox.Show("The file don't exist!", "Problems!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
// Write error.
Console.WriteLine(ex);
}

You already check on the presence of file in your first sniplet. There is no any need, for this code to be inside try/catch block.

Use throw:
try
{
if (!File.Exists("TextFile1.txt"))
throw (new Exception("The file don't exist!"));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

You only use a try/catch, when you have an unexpected error, or you are "expecting" an error from accessing a resource. That sounds a bit confusing, but in your cause, there is neither.
If however you opened as stream to READ a file without checking if it exists, that will then be necessary to have a try..catch.
All in all, try..catch's should be applied for safety, and where code is complex/length.

Related to this question following thread will be interesting
http://social.msdn.microsoft.com/Forums/en-NZ/winappswithcsharp/thread/1eb71a80-c59c-4146-aeb6-fefd69f4b4bb
File.Exists API was changed in window 8 and explaination is:
Currently the only way to check if a file exists is to catch the FileNotFoundException. As has been pointed out having an explicit check and the opening is a race condition and as such I don't expect there to be any file exists API's added. I believe the File IO team (I'm not on that team so I don't know for sure but this is what I've heard) is considering having this API return null instead of throwing if the file doesn't exist.
Approach with File.Exists is not thread safe and it was removed from API in windows 8. So just catch FileNotFoundException

Related

How should I handle unapproriate situations in C#

I'm a beginner and haven't had a job yet, so I never work experience with code.
My question is:
How should I handle situations, when user enters a value, that doesn't throw exception, but is unacceptable and and program should be closed.
Should I throw an exception with some message in catch block, or it would be enough to just show a message ?
Its really up to the requirements of the application that you are developing. But c# has a specific exception type for this:
InvalidArgumentException
And you can use it like this:
if (!ValidateUserInput(input))
throw new InvalidArgumentException ("input is invalid");
You can then catch that further up in the application and decide how to handle it
It all depends of You. Depends on what You want to achieve.
There is no ultimate answer to this.
It is good to do everything You said. Throw exeption in try catch block and then give a information for user and close program.
Additionally log the error with more informataion to a file or databases.
Message box is good, because is user firendly.
Throw exeption is also good because is very readable for developer - when they read You code they see this is a bad sitiation.
For example what to do:
try
{
if (IsErrorValidation())
{
throw new Exeption("You input wrong data");
}
}
catch (Exception e)
{
MessageBox.Show("Error" + e.Message );
CloseProgram();
}
You create new Exception with Your massage.
Better is create Your own type of Exeption for example ErrorValidationException or use the predefined InvalidArgumentException which exist in C#
try
{
if (IsErrorValidation())
{
throw new ErrorValidationException("You input wrong data");
}
}
catch (ErrorValidationException e)
{
MessageBox.Show("Error" + e.Message);
CloseProgram();
}
catch (Exeption e)
{
...
}
Then You can use this type of exception later and You can serve this type of exception in a different way

How to manage exception in catch block c#?

I have following code.
try
{
int s=10;
int k=0;
int stdsd = s / k;
}
catch (DivideByZeroException ext)
{
FileStream fs = new FileStream(#"C:\temp\data.txt", FileMode.Open);
//encountered an exception as file doesn't exist.
}
catch (Exception ex)
{
}
finally
{
//some code here.
}
In above code when exception occured then it will try to write that in one file in catch block.but when it trying to open that file that file doen't exists, so in such cases system crashed. I want to execute such critical code in finally block but due to exception in catch block it not going further to that line.
I know we can check file exists check but I don't want to check file exist check over here, I want to how to manage that in catch block.
can please assist the best way to manage exception in catch block.
You can't handle the exception generated from one catch block in a catch block associated with the same try/catch statement. Instead, you need an extra one:
catch (DivideByZeroException ext)
{
try
{
FileStream fs = new FileStream(#"C:\temp\data.txt", FileMode.Open);
}
catch (IOException e)
{
// Handle the exception here
}
}
Note that you should be using a using statement when opening the stream, so that you'll close it automatically whether or not an exception is thrown later.
I'd also recommend not having the code like this in the catch block directly - typically catch blocks should be short, for readability. Consider moving all the error-handling functionality into a separate method (or possibly even a separate class).
Just use another try {} catch {} ...
try {
// ...
try {
// try opening your file here ...
} catch (Exception) {
// ...
}
} catch (Exception) {
// ...
}
If you don't want to check the existence of the file "over here" (in the exception), then you could alternatively check the existence "over there", that is: earlier in the code.
What you want to do is to write an exception log to a file, as I understand it. So you could configure the correct log file handling earlier in the code, in the best case with a good log file handler. After this the only thing you have to do within the exception handler is to push your exception message to the log handler - which will then write this information properly to the file.
exceptions are very powerful future of any language that can not be ignored in most cases , but try to avoid it if possible
Look at this
String File = "File.txt";
System.IO.FileInfo fileinfo = new System.IO.FileInfo(File);
if(fileinfo.Exists)
{
using (System.IO.FileStream file = new System.IO.FileStream(File, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite))
{
// operation on file here
}
}else
{
using (System.IO.FileStream file = new System.IO.FileStream(File, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite))
{
// operation on file here now the file is new file
}
}

Customizing errors thrown based on default SystemExceptions

I have a line:
string[] cPathDirectories = Directory.GetDirectories(Properties.Settings.Default.customerFolderDirectory);
that will throw the error "Path is not of legal form" if the user didn't specify a search path (this setting is saved as String.Empty at this point). I would like throw this error to say, "Hey you idiot, go into the application settings and specify a valid path" instead. Is there a way to do this instead of:
...catch (SystemException ex)
{
if(ex.Message == "Path is not of legal form.")
{
MessageBox.Show("Hey you idiot, go into the application settings and specify a valid path","Error");
}
else
{
MessageBox.Show(ex.Message,"Error");
}
}
No, you need to check what the type of the exception is and catch that explicitly. Testing for strings in exception messages is a bad idea because they might change from one version of the framework to another. I'm pretty sure Microsoft doesn't guarantee that a message will never change.
In this case, looking at the docs you might be getting either a ArgumentNullException or ArgumentException, so you need to test for that in your try/catch block:
try {
DoSomething();
}
catch (ArgumentNullException) {
// Insult the user
}
catch (ArgumentException) {
// Insult the user more
}
catch (Exception) {
// Something else
}
Which exception you need here, I have no idea. You need to determine that and structure your SEH block accordingly. But always try to catch exceptions, not their properties.
Note the last catch is highly recommended; it ensures that if something else happens you won't get an unhandled exception.
you might check for an argument exception
...catch (SystemException ex)
{
if(ex is ArgumentException)
{
MessageBox.Show("Hey you idiot, go into the application settings and specify a valid path","Error");
}
else
{
MessageBox.Show(ex.Message,"Error");
}
}
That's an ArgumentException:
catch (ArgumentException) {
MessageBox.Show("Please enter a path in settings");
} catch (Exception ex) {
MessageBox.Show("An error occurred.\r\n" + ex.Message);
}
A couple ways to go about it.
First, just check the setting first before you make the GetDirectories() call:
if(string.IsNullOrEmpty(Properties.Settings.Default.customerFolderDirectory))
{
MessageBox.Show("Fix your settings!");
}
else
{
string[] cPathDirectories = Directory.GetDirectories(Properties.Settings.Default.customerFolderDirectory);
}
Or catch a more specific exception:
catch (ArgumentException ex)
{
MessageBox.Show("Hey you idiot, go into the application settings and specify a valid path","Error");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
I'd probably go with the former, since then you don't run into a penalty (albeit minor) for exception throwing and can do any other validation you want such as checking whether the path exists, etc.
If you prefer the latter, though, you can find the list of exceptions Directory.GetDirectories() throws here, so you can tailor your messages appropriately.
P.S. I also wouldn't call your users idiots, but that's between you and your god. :)
Yes, you can again throw exception from catch block, example:
catch (SystemException ex)
{
if(ex.Message == "Path is not of legal form.")
{
throw new Exception("Hey you idiot, go into the application settings and specify a valid path", ex);
}
else
{
MessageBox.Show(ex.Message,"Error");
}
}

why doesnt it write to file in exception

still giving problem
I have the following code. As long as I am in try { } it writes fine. But when there is an error, it doesn't write to log file. Not sure why
private static void jk(string kName, string path)
{
Job job;
try
{
// run some functions here and then write to the file
StreamWriter LJ = new StreamWriter("C:\\Lob.txt");
LJ.WriteLine("XXXXXXXXXXXX");
LJ.Close();
}
catch (InvalidException)
{
StreamWriter LJ = new StreamWriter("C:\\Lob.txt");
LJ.WriteLine("YYYYYYYYYYYYYYYY");
LJ.Close();
Console.WriteLine("Error: ");
return;
}
}
Because the only thing in your try is writing to the stream... and that's the same thing you try to do in the cacth. Why would that work?
The catch block executes only when the try block throws the exception (which appears to be a typo in the original post).
If the try succeeds, the catch is never executed.
If the try fails, it's because of a problem that must have occurred in writing to the log. When the catch executes, that problem most likely still exists, so the log within the catch will fail also.
Well, I don't know what type LJ is, and I certainly have never heard of a IncalidException. I am assuming that you just typed the code into the editor incorrectly. You should really just paste it in to avoid those types of errors.
Anyway, there are a few options:
LJ.WriteLine is not throwing an exception.
LJ.WriteLine is throwing an exception, but not of the same type you are catching (i.e., see if it works when you just catch { }).
The second call to LJ.WriteLine is also throwing an exception and you are catching (and perhaps swallowing) it further up the stack.
With your comment:
try fails because of some other problems but I am trying to log it
into the file
I assume that the exception is not thrown by LJ.WriteLine("XXXXXXXXXXXX");
If that's the case, you might just need to flush the StreamWriter. Try declaring LJ in a using block like this:
using (StreamWriter LJ = new StreamWriter("C:\\Lob.txt"))
{
LJ.WriteLine("XXXXXXXXXXXX");
try
{
...
LJ.WriteLine("XXXXXXXXXXXX");
}
catch (InvalidException)
{
LJ.WriteLine("YYYYYYYYYYYYYYYY");
Console.WriteLine("Error: ");
return;
}
}
Are you able to compile this code?
There are two things I see incorrect with the above.
It should be InvalidException not IncalidException
try
{
LJ.WriteLine("XXXXXXXXXXXX");
}
catch (InvalidException e)
{
LJ.WriteLine("YYYYYYYYYYYYYYYY");
Console.WriteLine("Error: {0}", e.Message);
return;
}

C# Nested Try Catch statements or methods?

Simple best practice question.
Should you nest try catch statements or just use methods.
For instance, if you have a method that opens a file does work and closes the file, you would have the open and close outside the try catch, or rather the close in the finally block.
Now if your open method fails, the method would assert right? So should your wrap that in a try catch block or should that be called from another method, which in turn as a try catch block?
In the context of a method that opens a file I would use a using statement vs a try catch. The using statement ensures that Dispose is called if an exception occurs.
using (FileStream fs = new FileStream(file, FileMode.Open))
{
//do stuff
}
does the same thing as:
FileStream fs;
try
{
fs = new FileStream(file, FileMode.Open);
//do Stuff
}
finally
{
if(fs!=null)
fs.Dispose();
}
Now that we have lambdas and type inference and some other stuff, there's an idiom that is common in other languages which now makes a lot of sense in C#. Your example was about opening a file, doing something to it, and then closing it. Well, now, you can make a helper method which opens a file, and also takes care of making sure to close / dispose / clean up, but calls out to a lambda you provide for the "do stuff" portion. This will help you get the complicated try/catch/finally dispose/cleanup stuff right in one place, and then use it over and over.
Here's an example:
public static void ProcessFile(string filePath, Action<File> fileProcessor)
{
File openFile = null;
try
{
openFile = File.Open(filePath); // I'm making this up ... point is you are acquiring a resource that needs to be cleaned up after.
fileProcessor(openFile);
}
finally
{
openFile.Close(); // Or dispose, or whatever.
}
}
Now, callers of this method don't have to worry about how to open the file or close / dispose of it. They can do something like this:
Helpers.ProcessFile("C://somefile.txt", f =>
{
while(var text = f.ReadLine())
{
Console.WriteLine(text);
}
});
This is a style question but for me I try to never have more than one level of try/catch/finally nesting in a single method. At the point you hit a nested try, you've almost certainly violated the 1 function = 1 operation principal and should use a second method.
Depends on what you are trying to do, but in most cases, nested try/catches are a sign of an over-complex function (or of a programmer who doesn't quite know how exceptions work!).
In the case of the open file, I'd use an IDisposable holder and a using clause, and so forgo the need of any explicit try/catch.
How about where you have related code that doesn't necessarily belong in a separate function of it's own right? Would this then be correct?
try
{
// Part 1 Code Here
try
{
// Part 2 Code Here
}
catch (Exception ex)
{
// Error from Part 2
}
}
catch (Exception ex)
{
// Error from Part 1
}
Most of the time I would break up the nested try/catch blocks into functions. But I have sometimes written code to catch and log all uncaught exceptions thrown by my application. But what if the logging code fails? So I have yet another try/catch around that just to prevent the user from seeing the default .NET unhandled exception dialog box. But even this code could very easily be refactored into functions instead of nested try/catch blocks.
try
{
try
{
DoEverything();
}
catch (Exception ex)
{
// Log the exception here
}
}
catch (Exception ex)
{
// Wow, even the log is broken ...
}
//create a switch here and set it to 0
try
{
DoChunk1();
//looks good. set the switch to 1
}
catch (Exception ex)
{
// Log the exception here
}
// check the switch, if it is still zero at this point then you may halt your program here; else set the switch back to zero and execute your next try catch statement. totally agree with breaking them down as mentioned above
try
{
DoChunk2();
//looks good. set the switch to 1
}
catch (Exception ex)
{
// Log the exception here
}
try
{
----
}
catch
{
try
{
---
}
catch
{
---
}
}

Categories

Resources