I have the following code. Is it ok to just have 1 catch exception ?. What other exception can this piece code can throw ?.
In exception handling , why can't we just have one exception and log all errors ?.
try {
if (File.Exists(inputFilename))
{
// do something
File.WriteAllText()
}
else {
// do somthing
}
}
catch (Exception ex)
{
_eventLog.WriteEntry(ex.Message + "\r\n" + ex.StackTrace, EventLogEntryType.Error);
}
Thanks
What other exception can this piece code can throw
You can see all the possible exceptions in the function page (MSDN):
ArgumentException
ArgumentNullException
PathTooLongException
DirectoryNotFoundException
etc.
why can't we just have one exception and log all errors
You would like to catch different type of exceptions if you want to handle it differently. For example:
try
{
if (File.Exists(inputFilename))
{
// do something
File.WriteAllText(path, contents);
}
else
{
// do somthing
}
}
catch (DirectoryNotFoundException dirNotFoundEx)
{
MessageBox.Show("Directory does not exist.Try to use diffrent folder.");
}
catch (Exception ex)
{
_eventLog.WriteEntry(string.Format("{0}{1}{2}", ex.Message, Environment.NewLine, ex.StackTrace), EventLogEntryType.Error);
}
}
The order of the catch blocks is important. see here
Related
I have the following code:
try
{
await _policyService.QueuePayment();
}
catch (Exception ex)
{
var slackError = new ErrorNotificationMessage("{ex.Message}");
await Notify(slackError);
}
I want to give more detail and log it to Slack if the Exception is a Security Exception, so I extended this try/catch block as follows:
try
{
await _policyService.QueuePayment();
}
catch (SecurityException ex)
{
throw new Exception("detailed message", ex);
}
catch (Exception ex)
{
var slackError = new ErrorNotificationMessage("{ex.Message}");
await Notify(slackError);
}
However this does not catch the rethrown Exception and log it to Slack. What am I missing here?
As it was already mentioned in comments by #canton7, you'd need a try-catch inside the catch (SecurityException ex) in order to catch it. However, as it was also mentioned, that doesn't make sense here. It's also not a common (or rather, correct) practice to wrap an exception just to change the error message.
Just use standard boolean logic:
try
{
await _policyService.QueuePayment();
}
catch (Exception ex)
{
var message = ex is SecurityException ? "Some very important message" : ex.Message;
var slackError = new ErrorNotificationMessage(message);
await Notify(slackError);
}
However this does not catch the rethrown Exception and log it to Slack. What am I missing here?
When we throw an exception explicitly it can be catched at the caller end by enclosing the method call in a try catch block. We cannot throw and catch the exception from a catch block in same method unless we add another try catch which does not actually make sense here.
What you should be doing is directly throwing that exception like :
try
{
await _policyService.QueuePayment();
}
catch (Exception ex)
{
if(ex is SecurityException)
{
// for security exception do something different
}
else
{
var slackError = new ErrorNotificationMessage("{ex.Message}");
await Notify(slackError);
}
}
I have the following code
public HttpResponseMessage AddDataToDatabase([FromBody] Data data)
{
try
{
var token = _tokenService.GetToken(Request.Headers.Authorization);
if (_pService.Permission(_tokenService.GetUserId(token), "Enable_Data"))
{
_noteService.AddData(data, _tokenService.GetUserId(token));
return Request.CreateResponse(HttpStatusCode.OK, "Data has been added to the case.");
}
throw new HttpResponseException(
Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Cannot add data because you don't have permission."));
}
catch (Exception exception)
{
if (exception is SqlException)
{
throw new HttpResponseException(
Request.CreateErrorResponse(HttpStatusCode.ServiceUnavailable, exception));
}
if (exception is ArgumentException)
{
throw new HttpResponseException(
Request.CreateErrorResponse(HttpStatusCode.Conflict, exception.Message));
}
throw;
}
}
I want to catch the Forbidden Exception like other exception in the catch block but not sure how to do that. The way I am returning Forbidden exception right now breaks unit tests which return SqlException and ArgumentExpception.
How can I throw exceptions correctly?
By far, the easiest way is to simply do it like this.
catch (Exception exception)
{
throw;
}
Unlike your code, this code also handles unanticipated exceptions instead of just SqlException and ArgumentException.
But why are you doing this? If you want the exception to propagate out to the caller, then simply remove the try...catch block in this method. Then just throw the desired exception in your code.
If you are capturing and converting third-party exceptions, the recommended approach is as follows.
catch (SqlException exception)
{
throw new HttpResponseException(
Request.CreateErrorResponse(HttpStatusCode.ServiceUnavailable, exception));
}
catch (ArgumentException exception)
{
throw new HttpResponseException(
Request.CreateErrorResponse(HttpStatusCode.Conflict, exception.Message));
}
you should probably replace your if logic in your catch by using more selective catch :
catch (SqlException exception)
{
throw new HttpResponseException(
Request.CreateErrorResponse(HttpStatusCode.ServiceUnavailable, exception));
}
catch (ArgumentException exception)
{
throw new HttpResponseException(
Request.CreateErrorResponse(HttpStatusCode.Conflict, exception.Message));
}
The uncaught exceptions will simplypass through (as when you you use throw;).
If you want to catch another type of exception, just add it to the list.
However, it is not very clear how your tests are broken. You should provide more details at this level if you want more help.
I'm not familiar with exception handling (not much of a developer).
How do I catch an exception when a database doesn't exist or is offline? Do I need to throw a new Exception? The following gets me the warning "Exception was unhandled by user code"
catch (Exception err)
{
if (err is OracleException)
{
//database does not exist?
ErrorMessage = err.Message;
throw new Exception(ErrorMessage);
}
else
{
ErrorMessage = err.Message;
con.Close();
throw new Exception(ErrorMessage);
}
The 'Catch' expression is used to handle the Exception. If you are throwing another Exception, it needs to be catched somewhere.
And C# allows you to catch more than one exceptions, so you can do this:
try
{
//TRY TO OPEN THE CONNECTION
}
catch (OracleException oraExcep)
{
//DO SOMETHING IF A OracleException
//ERROR IS HANDLED HERE
}
catch (Exception ex)
{
//DO SOMETHING ELSE
}
HttpWebRequest.GetReponse() has 4 types of Exceptions MSDN:
- System.InvlaidOperationException
- System.Net.ProtocalViolationException
- System.NotSupportedException
- System.Net.WebException
I'd like to catch all exceptions thrown by GetResponse() either with one catch{} for all GetResonse() exceptions or a catch{} for each type of exception thrown by GetResponse(), and catch all other exceptions with another catch{}.
In everything I've read, I only see WebException being caught. Is that because it catches everything that GetResponse() throws or because the other exceptions are more generic and will be thrown by others?
Consider the following code:
try
{
//a bunch of code...
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
//the rest of the try block...
}
catch (WebException e)
{
Console.WriteLine("You caught a WebException: " + e.Message);
throw;
}
catch (Exception e)
{
Console.WriteLine("This exception was not from getResponse: " + e.Message);
throw;
}
*I throw intentionally here. It needs to be dealt with by other callers further up the stack.
Alternatively, to catch all exceptions thrown by GetResponse, would I do something like this?
catch (WebException e)
{
Console.WriteLine("You caught a WebException: " + e.Message);
throw;
}
catch (InvalidOperationExceltion e)
{
// Do stuff...
}
catch (ProtocolViolationException e)
{
// Do stuff...
}
catch (NotSupportedException e)
{
// Do stuff...
}
catch (Exception e)
{
// Do stuff...
}
I'm sure it's just as straightforward as I think it is, but I can't find examples of people catch more than WebException.
Thanks!
Use the second code, but why would you handle all other exceptions when you're already handling the exceptions thrown by GetResponse? The extra "catch" is unneccessary IMO.
is it possible to do something like the following:
I want to catch a custom exception and do something with it - easy: try {...} catch (CustomException) {...}
But then i want to run the code used in the "catch all" block still run some other code which is relevant to all catch blocks...
try
{
throw new CustomException("An exception.");
}
catch (CustomException ex)
{
// this runs for my custom exception
throw;
}
catch
{
// This runs for all exceptions - including those caught by the CustomException catch
}
or do i have to put whatever i want to do in all exception cases (finally is not an option because i want it only to run for the exceptions) into a separate method/nest the whole try/catch in another (euch)...?
I generally do something along the lines of
try
{
throw new CustomException("An exception.");
}
catch (Exception ex)
{
if (ex is CustomException)
{
// Do whatever
}
// Do whatever else
}
You need to use two try blocks:
try
{
try
{
throw new ArgumentException();
}
catch (ArgumentException ex)
{
Console.WriteLine("This is a custom exception");
throw;
}
}
catch (Exception e)
{
Console.WriteLine("This is for all exceptions, "+
"including those caught and re-thrown above");
}
Just do the overall catch and check to see if the exception is that type:
try
{
throw new CustomException("An exception.");
}
catch (Exception ex)
{
if (ex is CustomException)
{
// Custom handling
}
// Overall handling
}
Alternately, have a method for overall exception handling that both call:
try
{
throw new CustomException("An exception.");
}
catch (CustomException ex)
{
// Custom handling here
HandleGeneralException(ex);
}
catch (Exception ex)
{
HandleGeneralException(ex);
}
No, it doesn't do this way, you either catch a specific exception (linearly) or a generalisation. If you wish to run something for all exceptions you would need to keep a record of whether or not an exception has been thrown, perhaps what it was etc, and use finally, or another contrived, probably more 'messy' and verbose, mechanism.