As far as I know, you are supposed to only use try/catch when you will actually handle the exception and not just report&log it and then crash the application. Otherwise, you are better off just checking different scenarios where it makes sense (e.g. if sth==null) or - if your purpose is just to log the exception and crash the application - to use AppDomain.UnhandledException. But is this always the case and why?
Suppose the following method, which accepts an array and returns MemoryStream after doing some database and filesystem operations.
MemoryStream Read (int[] IDs)
{
try
{
using (SqlConnection connection = new SqlConnection(connection_string))
{
connection.Open();
// a bunch of code executing SQL queries & constructing MemoryStream, which is returned at the end of the block
}
}
catch (Exception e)
{
// report the exception to the user & log it
throw; // pointles??
}
}
There are multiple situations that can be considered exceptional/unwanted behavior, such as:
- argument (IDs[]) being null,
- failure to establish an SQL connection,
- failure to execute a specific SQL query.
All these cases are considered exceptional, still putting everything inside a try/catch if you only want to log an exception (then crash) is probably bad practice - but why? What would be the best handling behavior in the above case? Avoid try/catch completely, check null references using an if statement (return null in such case) and use AppDomain.UnhandledException to log everything else? Use try/catch, but still check for null references inside using if statements (and return in that case)? Something else?