Byyo
Byyo

Reputation: 2243

Summarize try / catch

Is there a way to get this shorter?

I have single lines with method calls but in exception case each needs a seperate error message.

try
{ 
    ReadFile(); 
}
catch
{ 
    Message.Show("Error reading File"); 
}
try 
{ 
    ReadData(); 
}
catch 
{ 
    Message.Show("Error reading Data"); 
}
try 
{ 
    ValidateData(); 
}
catch
{
    Message.Show("Error validating Data"); 
}
try
{
    SaveData();
}
catch 
{ 
    Message.Show("Error saving Data");
}

Upvotes: 0

Views: 69

Answers (2)

Mikhail Tulubaev
Mikhail Tulubaev

Reputation: 4251

  1. Place throw new Exception(<yourMessage>) into your methods and place this methods into one big try..catch block. Logically it is correcter, because every exception belongs to method, not to this realization of methods;
  2. Place try..catch into methods and return int or enum status code from each method, and create message based on this status code;
  3. Throw different types of exception, and depends on it show corresponding message;
  4. Add global exception handling to your application

Upvotes: 0

laszlokiss88
laszlokiss88

Reputation: 4071

Throw exceptions like this:

throw new Exception("Error reading File");
throw new Exception("Error reading Data");

and with that you can change your code

try
{ 
    ReadFile(); 
    ReadData(); 
}
catch (Exception ex)
{ 
    Message.Show(ex.Message); 
}

Or you can throw specific exceptions like ReadDataException or ReadFileException and whit that

try
{ 
    ReadFile(); 
    ReadData(); 
}
catch (ReadFileException)
{ 
    Message.Show("Error reading File"); 
}
catch (ReadDataException)
{ 
    Message.Show("Error reading Data"); 
}

Upvotes: 3

Related Questions