Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# try-catch-else

One thing that has bugged me with exception handling coming from Python to C# is that in C# there doesn't appear to be any way of specifying an else clause. For example, in Python I could write something like this (Note, this is just an example. I'm not asking what is the best way to read a file):

try
{
    reader = new StreamReader(path);
}
catch (Exception)
{
    // Uh oh something went wrong with opening the file for reading
}
else
{
    string line = reader.ReadLine();
    char character = line[30];
}

From what I have seen in most C# code people would just write the following:

try
{
    reader = new StreamReader(path);
    string line = reader.ReadLine();
    char character = line[30];
}
catch (Exception)
{
    // Uh oh something went wrong, but where?
}

The trouble with this is that I don't want to catch out of range exception coming from the fact that the first line in the file may not contain more than 30 characters. I only want to catch exceptions relating to the reading of the file stream. Is there any similar construct I can use in C# to achieve the same thing?

like image 930
Martin Sherburn Avatar asked Jul 24 '09 12:07

Martin Sherburn


3 Answers

Catch a specific class of exceptions

try
{
    reader = new StreamReader(path);
    string line = reader.ReadLine();
    char character = line[30];
}
catch (IOException ex)
{
    // Uh oh something went wrong with I/O
}
catch (Exception ex)
{
    // Uh oh something else went wrong
    throw; // unless you're very sure what you're doing here.
}

The second catch is optional, of course. And since you don't know what happened, swallowing this most general exception is very dangerous.

like image 115
Henk Holterman Avatar answered Oct 17 '22 20:10

Henk Holterman


You could write it like:

bool success = false;
try {
    reader = new StreamReader(path);
    success = true;
}
catch(Exception) {
    // Uh oh something went wrong with opening the file for reading
}
finally {
    if(success) {
        string line = reader.ReadLine();    
        char character = line[30];
    }
}   
like image 45
Johan Kullbom Avatar answered Oct 17 '22 21:10

Johan Kullbom


You can do this:

try
{
    reader = new StreamReader(path);
}
catch (Exception)
{
    // Uh oh something went wrong with opening the file for reading
}

string line = reader.ReadLine();
char character = line[30];

But of course, you will have to set reader into a correct state or return out of the method.

like image 6
Adrian Godong Avatar answered Oct 17 '22 20:10

Adrian Godong