| View previous topic :: View next topic |
| Author |
Message |
NINTENDO Grandmaster Cheater Supreme
Reputation: 0
Joined: 02 Nov 2007 Posts: 1371
|
Posted: Thu May 20, 2010 4:01 am Post subject: [C#] IO and TRY CATCH |
|
|
Do I have to try catch IO operations to make them safe? And when I say safe I mean that they not crash the program.
Most of the other exceptions you can like prevent with code but io??
_________________
Intel over amd yes. |
|
| Back to top |
|
 |
Dark Byte Site Admin
Reputation: 474
Joined: 09 May 2003 Posts: 25953 Location: The netherlands
|
Posted: Thu May 20, 2010 7:35 am Post subject: |
|
|
not sure about C#, but other languages have no problem catching IO exception (those are just normal GPF exceptions)
_________________
Tools give you results. Knowledge gives you control.
Like my help? Join me on Patreon so i can keep helping |
|
| Back to top |
|
 |
hcavolsdsadgadsg I'm a spammer
Reputation: 26
Joined: 11 Jun 2007 Posts: 5801
|
Posted: Thu May 20, 2010 9:08 am Post subject: |
|
|
| don't use exceptions for stuff like checking to see if you've read an entire file, etc. if you expect it to happen, you probably don't need to catch it.
|
|
| Back to top |
|
 |
atom0s Moderator
Reputation: 205
Joined: 25 Jan 2006 Posts: 8587 Location: 127.0.0.1
|
Posted: Sat Jun 12, 2010 7:33 pm Post subject: |
|
|
If an exception is raised it will be unhandled if you don't have try/catch handlers. You can't prevent the crash from happening because the application does not know what to do when the exception occurs without them.
For example, a simple IO func that can/will throw an exception:
| Code: | // This will throw 'System.IO.FileNotFoundException'
System.IO.FileStream fStream = System.IO.File.Open("C:\\Some_Fake_File.txt", System.IO.FileMode.Open);
fStream.Close(); |
If the file doesn't exist it will throw System.IO.FileNotFoundException. If you don't catch the exception your application throw the error through .NETs handler. If the exception isn't critical the application can continue if the user tells it to. But this can/will lead to unwanted functionality. You should use try/catch anywhere you have the ability for an exception to be raised, even more so if the exception is not created by you.
So this would be an example of handling it:
| Code: | try
{
System.IO.FileStream fStream = System.IO.File.Open("C:\\Some_Fake_File.txt", System.IO.FileMode.Open);
fStream.Close();
}
catch (Exception ex)
{
MessageBox.Show("Caught exception: " + ex.ToString());
} |
_________________
- Retired. |
|
| Back to top |
|
 |
|