Sometimes I have this situation when it's quite easier to wrap whole piece of code in try-catch block rather than do a lot of checking which violently reduce code readability. For example, this
var result = string.Empty;
if (rootObject != null)
{
if (rootObject.FirstProperty != null)
{
if (rootObject.FirstProperty.SecondProperty != null)
{
if (!string.IsNullOrEmpty(rootObject.FirstProperty.SecondProperty.InterestingString))
{
result = rootObject.FirstProperty.SecondProperty.InterestingString;
}
}
}
}
I really prefer to do like this
var result = string.Empty;
try
{
result = rootObject.FirstProperty.SecondProperty.InterestingString;
}
catch { }
But after code review I often hear from my mentor that I should avoid try-catch blocks when it's possible to make simple checking. Is it really so critical and each try-catch block eating a lot of system resources (relatively)? Is this resources used only when error raised or each case (successfull or not) is equally "heavy"?
The best practices for Exception Handling in C# are based on logging the exception. The log should be to logging library to keep a record of the exceptions. Log exceptions using log4net, NLog, and other frameworks used for the same purpose.
Disadvantages. Using exceptions for error handling has two disadvantages. First, exceptions can trap only runtime errors. Therefore, a PL/SQL program cannot trap and recover from compile-time (syntax and semantic) errors such as table or view does not exist.
NET, an exception is an object that inherits from the System. Exception class. An exception is thrown from an area of code where a problem has occurred. The exception is passed up the stack until the application handles it or the program terminates.
Exceptions provide a way to transfer control from one part of a program to another. C# exception handling is built upon four keywords: try, catch, finally, and throw.
Whether exceptions are heavyweight or lightweight is completely irrelevant. A thrown exception that could have been easily prevented is a bug. Do not catch the exception: fix the bug so that you don't have to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With