Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I'm inserting data to a database and I guess some kind of exceptions might occur here, possible more than one?
ussually I used to write something like this:
try
{
//Execution code
}
catch(Exception ex)
{
// log error and throw it
}
And I think it's better to catch some specific exception instead of (Exception ex) something like this:
try
{
// my possibly bad code which inserts data to db
var someEntity = CreateEntityFromDTO(someDTO);
_context.SomeThing.Add(someEntity);
await _context.SaveChangesAsync(cancellationToken);
}
catch(MySpecificException mse)
{
// log error and throw it
}
What might be best practice when it's about catching exception while inserting data to db ?
Thanks
Cheers
You could make your SpecificExceptions inherit from another higher level DatabaseException and handle all Database Exceptions in one catch clause like
public class DatabaseException : Exception {}
public class MySpecificException : DatabaseException {}
public class YetAnotherDBSpecificException : DatabaseException {}
try
{
// insert data.
}
catch(DatabaseException dbEx)
{
// A database exception occured.
Console.Log(dbEx.Message);
}
catch(Exception other)
{
// Non db exception occured.
Console.Log(other.Message);
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Code:
using (var reader = await cmd.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
var recibir = reader.VisibleFieldCount;
var rear = reader;
response.Add(new Cuota
{
opcion = (int)reader["PC_NUMERO_OPCION"],
cuota = (int)reader["PC_NUMERO_CUOTAS"]
});
}
}
I am trying to get the exceptions of SQL Server, what are the corresponding methods?
In general, you can catch a SQL Exception using the SQLException class. It works like this:
try
{
// your code that calls the database here
}
catch (SqlException e)
{
// your code that handles the Sql Exception
}
I typically add a double catch, just in case there is some other error in my code tht isn't SQL related:
try
{
// your code that calls the database here
}
catch (SqlException e)
{
// your code that handles the Sql Exception
}
catch (Exception ex)
{
// your code that handles normal exceptions
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I am trying to update some documents in DocumentDb / CosmosDb, and if that fails, need to do something else, and then if that fails to log it out...
try {
do a thing w/ database
}
catch (DocumentClientException dce1) {
try {
do another, alternative thing w/ database
}
catch (DocumentClientException dce2) {
log to app insights.
}
}
I'm not sure about this, it seems clunky.. what do you guys think?
For additional bonus points, I need to do this quite frequently.. so something that I can farm off somewhere would be even better ;)
Personally I'd avoid intermixing exception flow with a functional logic flow. It can get brittle. Instead, convert the exception into a logical flag and use it in ordinary logic constructs.
So step 1 is catch the exception and set a variable or return value based on it, and wrap this in an independent method to mask the messiness from everyone else:
bool TryDoSomethingWithDataBase()
{
try
{
//Do thing that could fail
return true;
}
catch(SpecificException ex)
{
return false;
}
}
bool TryDoSomethingElseWithDataBase()
{
try
{
//Do thing that could fail
return true;
}
catch(SpecificException ex)
{
return false;
}
}
Step 2 is to write the logic as usual:
if (!TryDoSomethingWithDatabase())
{
if (!TryDoSomethingElseWithDatabase())
{
LogFatalError();
}
}
Or
var ok = TryDoSomethingWithDatabase();
if (ok) return;
ok = TryDoSomethingElseWithDatabase();
if (ok) return;
LogFatalError();
Why would your thing with the Database fail? You would be better coding for the conditionals you are aware of and expecting and do different things if you want to go into a different logic for processing the result.
Try catch will catch anything and everything, so if your connection to the db fails etc or if you are trying to read or insert malformed data etc.
Try catch does have various exceptions that you can investigate further and catch the specific exception you are interested in.. e.g.
try
//try something
catch (Exception ex)
{
if (ex is FormatException || ex is OverflowException)
{
//Do something specific;
return;
}
throw;
}
This is ok but if you say you'll have this over and over it's better to extract that logic and reuse it.
One way of doing this is to have a method that accept the first and section actions as parameters, for example:
public void TryThis(Action doFirst, Action doSecond)
{
try {
doFirst();
}
catch (DocumentClientException dce1) {
try {
doSecond();
}
catch (DocumentClientException dce2) {
log to app insights.
}
}
}
And then use it like so:
public void DoSomethig1()
{
...
}
public void DoSomething2()
{
...
}
TryThis(DoSomething1, DoSomething2)
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Is it reasonable to think I can write a void function to take in an Exception and output the stuff that a catch block normally would? Here's an example of my exception catcher (which I would make individual ones for common exceptions I handle):
private void exCatch(Exception ex)
{
MessageBox.Show("ERROR - " + blah blah blah + ex.ToString(), blah blah);
}
Here it is in practice:
try
{
stuff
}
catch (Exception e)
{
exCatch(e);
}
Is this an efficient way to handle exceptions? If this is reasonable, do people do this? It seems like it could speed up your coding not having to copy paste all your exception junk over and over. Thanks for any help!
There is no problem with that at all. In fact, adding functions to reduce code repetition is definitely advisable. Then if you want to change say the MessageBox buttons you change it once and you're done everywhere.
One note is that you should consider only catching certain types of exceptions that you're expecting. If you're catching an exception it should be because you know where it came from and exactly what to do with it. Or else you might be catching something that should be handled at a higher level and your app can get into an invalid state. Here's an example.
ArgumentNullException
FormatException
OverflowException
Are the exceptions that Int32.Parse(string) throws. Lets say you know you wont be passing in Null this is how MSDN shows you should handle the function:
using System;
public class Example
{
public static void Main()
{
string[] values = { "+13230", "-0", "1,390,146", "$190,235,421,127",
"0xFA1B", "163042", "-10", "007", "2147483647",
"2147483648", "16e07", "134985.0", "-12034",
"-2147483648", "-2147483649" };
foreach (string value in values)
{
try {
int number = Int32.Parse(value);
Console.WriteLine("{0} --> {1}", value, number);
}
catch (FormatException) {
Console.WriteLine("{0}: Bad Format", value);
}
catch (OverflowException) {
Console.WriteLine("{0}: Overflow", value);
}
}
}
}
https://msdn.microsoft.com/en-us/library/b3h1hf19(v=vs.110).aspx
Always look up the exceptions that a method can throw and always document those that you are catching and throwing in your methods.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Is it a good idea to wrap the return value of the functions in a class. It provides ease of coding and you can avoid try...catch
I'm taking about doing something like this.
public class ResultWrapper
{
public bool Success{get;set;}
public Exception ErrorMessage{get;set;}
public object Result{get;set;} //not object essentially(any type)
public Result()
{
Success=false;
ErrorMessage="";
Result=null;
}
}
public ResultWrapper DoSomething(parameters....)
{
var result=new ResultWrapper()
try
{
}
catch(Exception ex)
{
result.Error=ex;
}
return result;
}
and then calling it like
static void main()
{
var result=DoSomething(parameters...);
if(result.Success)
{
//Carry on with result.Result;
}
else
{
//Log the exception or whatever... result.Error
}
}
EDIT:
consider this
static void main()
{
var result=Login(); //throws an exception
if(result.Success)
{
//retrive the result
//carry on
result=PostSomeStuff(parameter);
if(result.Success)
{
}
else
{
Console.WriteLine("Unable to Post the data.\r\nError: {0}",result.Error.Message);
}
}
else
{
Console.WriteLine("Unable to login.\r\nError: {0}",result.Error.Message);
}
}
isn't it simpler then to wrapping a try..catch outside of each function???
static void main()
{
try
{
var result=Login();
var result1=result=PostSomeStuff(parameter);
// a lot of functions doing seprate things.
}
catch(Exception ex)
{
//what to do...?
}
}
No, this is an anti-pattern. If there is any exception that you don't know how to handle then let it propagate up. Returning exception objects in the return value is a very bad idea when the language has support for exceptions.
If the method is successful it should return the value directly; if it fails it should throw an exception. (Caveat: Some methods might return bool indicating success or failure, and store the result in an out parameter. For example, int.TryParse(), Dictionary<TKey, TValue>.TryGetValue(), etc. Since exceptions can be expensive, some operations might be better suited to simply return a flag indicating failure if failure is expected to be frequent, but this should be a rare occurrence.)
Generally no. There may be specific cases where it's a good idea, but I wouldn't recommend it as a default.
It will make it impossible to allow the exception to "bubble up" until it gets to a good place to handle it. It will make the code harder to understand.
This is awful. Think how many if statement would be added to your code, just to check if an exception was thrown.
Also, think of it this way: if this were a great idea, then the .NET Framework itself would do this. Have you ever seen this pattern anywhere in .NET? I haven't.
You should almost always match the semantics of what the framework does that you are using, otherwise you end up with a weird mish-mash. Soon you have 10 competing coding "standards."
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed last year.
Improve this question
I am trying to handle two different WebException's properly.
Basically they are handled after calling WebClient.DownloadFile(string address, string fileName)
AFAIK, so far there are two I have to handle, both WebException's:
The remote name could not be resolved (i.e. No network connectivity to access server to download file)
(404) File not nound (i.e. the file doesn't exist on the server)
There may be more but this is what I've found most important so far.
So how should I handle this properly, as they are both WebException's but I want to handle each case above differently.
This is what I have so far:
try
{
using (var client = new WebClient())
{
client.DownloadFile("...");
}
}
catch(InvalidOperationException ioEx)
{
if (ioEx is WebException)
{
if (ioEx.Message.Contains("404")
{
//handle 404
}
if (ioEx.Message.Contains("remote name could not")
{
//handle file doesn't exist
}
}
}
As you can see I am checking the message to see what type of WebException it is. I would assume there is a better or a more precise way to do this?
Based on this MSDN article, you could do something along the following lines:
try
{
// try to download file here
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
if (((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.NotFound)
{
// handle the 404 here
}
}
else if (ex.Status == WebExceptionStatus.NameResolutionFailure)
{
// handle name resolution failure
}
}
I'm not certain that WebExceptionStatus.NameResolutionFailure is the error you are seeing, but you can examine the exception that is thrown and determine what the WebExceptionStatus for that error is.