Is this possible to retrieve the object which cause an InvalidOperationException - c#

I have this piece of code :
try{
// other instructions
customer.Create(act.ID, act.AccountId.Value, act.AccountName, act.Referer);
// other instructions
}
catch (Exception ex)
{
Logging.Trace(ex);
}
In some cases, AccountId is null, and getting the Value like that threw an InvalidOperationException.
My question is : in a catch section, is this possible to retrieve the fact that AccountId was null ?
Using StackTrace or, something like that. I search on google but nothing appears.
As much as possible, I do not want to modify the structure of the code before, using if( Account != null) etc...
Thanks in advance for any kind of help.

Related

Ignoring exceptions vs throwing it explicitly

Is it alright to return an empty object in case of an exception or should we throw the exception so that caller may know what has gone wrong?
public async Task<UserInfoModel> GetUserInfoByRole(Role role)
{
UserModel userInfo = new UserModel();
try
{
// do something
}
catch (Exception ex)
{
// do logging
// throw;
}
return userInfo;
}
It depends if you are creating a class, component, ... for others to use, you obviously should throw an exception. because they need to know about it and handle the exception the way that suits them.
If it is a method in your own code, may be returning a null value would be sufficient, because you might just check the return value and if it is null you know that there was an error and you don't want to program break because of the exception, otherwise you will need another exception handling again.

How should I handle unapproriate situations in C#

I'm a beginner and haven't had a job yet, so I never work experience with code.
My question is:
How should I handle situations, when user enters a value, that doesn't throw exception, but is unacceptable and and program should be closed.
Should I throw an exception with some message in catch block, or it would be enough to just show a message ?
Its really up to the requirements of the application that you are developing. But c# has a specific exception type for this:
InvalidArgumentException
And you can use it like this:
if (!ValidateUserInput(input))
throw new InvalidArgumentException ("input is invalid");
You can then catch that further up in the application and decide how to handle it
It all depends of You. Depends on what You want to achieve.
There is no ultimate answer to this.
It is good to do everything You said. Throw exeption in try catch block and then give a information for user and close program.
Additionally log the error with more informataion to a file or databases.
Message box is good, because is user firendly.
Throw exeption is also good because is very readable for developer - when they read You code they see this is a bad sitiation.
For example what to do:
try
{
if (IsErrorValidation())
{
throw new Exeption("You input wrong data");
}
}
catch (Exception e)
{
MessageBox.Show("Error" + e.Message );
CloseProgram();
}
You create new Exception with Your massage.
Better is create Your own type of Exeption for example ErrorValidationException or use the predefined InvalidArgumentException which exist in C#
try
{
if (IsErrorValidation())
{
throw new ErrorValidationException("You input wrong data");
}
}
catch (ErrorValidationException e)
{
MessageBox.Show("Error" + e.Message);
CloseProgram();
}
catch (Exeption e)
{
...
}
Then You can use this type of exception later and You can serve this type of exception in a different way

Throwing exceptions at multiple points (refactoring)

I'm writing a function that takes user input, runs a procedure in our database, and compares the values. Along the way, I need to check that we've received proper input and then that the query has returned an acceptable value.
private void DoTheThing(int? userInput1, int? userInput2, int valuePassedIn)
{
if (userInput1 == null || userInput2 == null)
{
Exception ex = new Exception();
ex.Data.Add("Message", "You screwed up.");
throw ex;
}
var queryResult = 0; //execute a query using the non-null inputs
if (queryResult == null) //or otherwise doesn't return an acceptable value
{
Exception ex = new Exception();
ex.Data.Add("Message", "some other thing happened");
throw ex;
}
else
{
//We're good, so do the thing
}
}
A quick note about this: I'm aware of the argument against exceptions as flow control and that I'd be better off checking the user's input before I even get this far. I won't get into all the details, but please accept that I'm kind of stuck writing the function this way.
That having been said, here's my question:
Given that the only differences between the 2 exceptions here is the message and the time at which they are thrown, how can I clean this code up to be both DRY and avoid running unnecessary code after determining that there will be a problem?
I thought about using a goto and placing the error code there, but that really only moves the problem around. If I move the exception code to the bottom and check for a message variable (or something similar), then I'm just running code that doesn't need to be run in the first place.
I suggest not throwing Exception (which means something went wrong, no comments are available), but ArgumentNullException and InvalidOperationException classes. Another amendment is avoding arrow-head
antipattern:
private void DoTheThing(int? userInput1, int? userInput2, int valuePassedIn)
{
// What actually went wrong? An argument "userInput1" is null
if (null == userInput1)
throw new ArgumentNullException("userInput1");
else if (null == userInput2)
throw new ArgumentNullException("userInput2"); // ...or userInput2 is null
var queryResult = executeSomeQuery(userInput1, userInput2, valuePassedIn);
// What went wrong? We don't expect that null can be returned;
// so the operation "executeSomeQuery" failed:
// we've provided validated (not null) values and got unexpected return.
// Let it have been known.
if (null == queryResult)
throw new InvalidOperationException(
String.Format("Query ({0}, {1}, {2}) returned null when bla-bla-bla expected",
userInput1, userInput2, valuePassedIn));
// We're good, so do the thing
// Note that's there's no "arrow-head antipattern":
// we're not within any "if" or "else" scope
}
Edit: Since every *Exception is inherited from Exception you can put some info into Data:
Exception ex = new ArgumentNullException("userInput1");
ex.Data.Add("Some key", "Some value");
throw ex;
but often Message is a far better place to explain what had heppened.
You might be better off creating a BadInputException class and a NullQueryResultException class. These do two different things and throwing a specific exception is better than throwing a generic Exception(...). In fact I think FXCop or Visual Studio's Code Analysis will give you a warning about throwing generic Exceptions.
It's not really all that much new code to write.
public class BadInputException : Exception
{
public BadInputException()
{
this.Data.Add("Message", "You screwed up.")
}
}
Then instead of this:
Exception ex = new Exception();
ex.Data.Add("Message", "You screwed up.");
throw ex;
Do this:
throw new BadInputException();
Edit: moved the "You screwed up" message from the Message property to the Data collection to match what the OP wants.
I would create a method:
private void CheckResult(bool cond, string msg, string info) {
if (!cond)
return;
Exception ex = new Exception();
ex.Data.Add(msg, info);
throw ex;
}
and call
CheckResult(userInput1 == null || userInput2 == null, "Message", "You screwed up.");
and
CheckResult(queryResult == null, "Message", "You screwed up.");
I think the QuestionRefactoring Guard Clauses is helpful for you .
There are something about this in Replace Nested Conditional with Guard Clauses.
Hope it's useful.

How to read Google.GData.Client.GDataRequestException

I am writing a youtube upload software. Actually my question is generic here.
The Google.GData.Client produces an exception. But I don't know how to reach in order to write ?
I mean how do I access it ? I tried with E. but there is no Google.Gdata
I need to access Google.GData.Client.GDataRequestException.ResponceString
You need to change your catch clause to specify the type of exception (in your case, Google.GData.Client.GDataRequestException) so that you can access its members.
catch (Google.GData.Client.GDataRequestException ex)
{
Console.WriteLine(ex.ResponseString);
}
try {
// your GDataRequest code goes here
} catch (GDataRequestException e ) {
// your error code goes here
}

Retrieving error codes from SQLite when using ExecuteNonQuery()

In my C# project, I'm using System.Data.SQLite.dll downloaded from CodeProject.
My problem is as per the title - how to get the error codes after calling SqliteCommand.ExecuteNonQuery() function?
Error codes such as SQLITE_CONSTRAINT, SQLITE_BUSY, SQLITE_LOCKED as shown here.
use the Exception.StackTrace or the SQLiteException.ErrorCode
try
{
}
catch(SQLiteException ex)
{
string code = ex.ErrorCode;
}
I'm going to add to this to help others, if you're developing in .NET. Use the
SQLiteErrorCode enumeration to test the result, cast the ErrorCode:
try
{
}
catch(SQLiteException ex)
{
SQLiteErrorCode sqlLiteError= (SQLiteErrorCode)ex.ErrorCode;
//Do whatever logic necessary based of the error type
}
Good question.
System.Exception does not have a member by the name ".ErrorCode"
Catch Ex As SQLiteException
E = Ex.ResultCode
Return E
End Try

Categories

Resources