System.NullReferenceException On WCF call - c#

I'm having quite a difficulty trying to trace this bug. At first I thought it was linq SQL data that's causing NRE because every time I look at the tracer log, it gives me the .cs line 37 which is pointed to my sql (stored proc) call. The reason I suspect this, the result of this sproc is null (not NULL) but there's no row return for all the fields. What I did was to put data on it, and now comes the frustration; I still get the same error. Maybe it's worth mentioning that when I use the WCF as reference(not servicereferences) a DLL straight to bin then it works perfect, only when I try to use the client (mywebservice.client) one.
Any ideas where I should be looking? It is on app.config? Also, I'm using a console app to access the WCF.
This is my code:
public static List<usp_GetPaymentsResult> GetScheduledPayment(DateTime DateRun, int Fee)
{
try
{
PaymentDataContext DBContext = new PaymentDataContext();
return DBContext.usp_GetPayments(DateRun, Fee).ToList(); //line 37
}
catch (SqlException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}

public static List<usp_GetPaymentsResult> GetScheduledPayment(DateTime DateRun, int Fee)
{
using(var context = new PaymentDataContext())
{
var payments = DBContext.usp_GetPayments(DateRun, Fee);
if (payments == null)
{
// bad database! handle error here
}
return payments.ToList();
}
}
Please note the following:
A DBContext is IDisposable. Put it in a using block, or it will
not be disposed in a timely fashion.
Your exception handling blocks did nothing but trash the exception.
If you want to rethrow an exception, use throw; without the
variable. It will rethrow the exception. Using the variable ex again
will overwrite it's stacktrace and valuable information will be lost.
However, as your blocks would have been nothing but rethrowing an
exception, you can just not catch it. Same result.
Check the result for null before you call an extention method like
.ToList() on it.
Finally, WCF Webservices are not magic. You can put breakpoints there and debug them. If you have problems doing so, maybe it would be a good idea to ask a question about that with more details about your webservice setup (VS internal or IIS Express or IIS?) and your project structure. Guessing the error based on line number is so 80s :)

After a frustrating 30 mins trying to debug a WCF NullReferenceException, turned out I had corrected an error in the WCF method structure, but hadn't refreshed the service in the calling client.

Related

try-catch for logging purposes?

According to this answer: https://stackoverflow.com/a/1722991/680026
you should only use try-catch if you really do something there besides logging:
Don't catch an exception if you're only going to log the exception and
throw it up the stack. It serves no meaning and clutters code.
But what about logging information that are not available at the higher level?
eg:
private void AddSomethingToTable(string tablename, string fieldname) {
try {
InsertFieldToTable(tablename, fieldname);
} catch (Exception ex) {
log.ErrorFormat("Could not insert field '{0}' into table '{1}'", fieldname, tablename);
throw;
}
}
private void main() {
try {
AddSomethingToTable("users","firstname");
AddSomethingToTable("users","lastname");
AddSomethingToTable("users","age");
} catch (Exception ex) {
MessageToUser("Sorry. Saving did not work.",ex);
}
}
As you can see: In my (completely made up) example I log the information about the field that did cause the error. This could be some good information to start finding the error.
So even though I only logged the error, this information could be crucial and be lost outside that method.
Is this a valid use of try-catch here or are there other suggested ways to log that? (I don't think that just always logging this info (regardless if an error occurred or not) would be a valid solution)
I think you answered your own question with
But what about logging information that are not available at a higher instance
and
this information could be crucial and be lost outside that method
I dislike hard and fast "always do X and never Y", because there are times where it is necessary to go against so-called "best practice" in order to do what is best for your application.
If logging the information is necessary to fix the issue, and you lose this information if you don't log it immediately, then log the information.
There is nothing wrong in what you are trying to do. The idea of the other question/answer was that it is better to log the error at the place where you really handle it. In .NET every exception contains a stack trace. This means that upper layer can report location in the code that has generated this error. Doing that in one place instead of many is way more meaningful. This was their idea.
From your linked quesion:
The basic rule of thumb for catching exceptions is to catch exceptions if and only if you have a meaningful way of handling them.
I put emphasis on "The basic rule of thumb" as it's not a law. It's a best practice. i.e. follow it until you have a good motivation to not do so.
If you catch exceptions to include information you probably should throw a new meaningful exception with more context information. something like:
try
{
//kldfsdölsdöls
}
catch (Exception ex)
{
throw new MoreDetailedException("Text with context data", ex);
}
That way you'll get all context information for each stack level collected into the same exception (since you included the inner exception in it). Thus the log entry in the top level will contain ALL information in the same line.
But what about logging information that are not available at a higher
instance?
You can pass those information back to caller while re-throwing the exception
private void AddSomethingToTable(string tablename, string fieldname) {
try {
InsertFieldToTable(tablename, fieldname);
} catch (Exception ex) {
string str = string.Format("Could not insert field '{0}' into table '{1}'", fieldname, tablename);
throw new Exception(str, ex);
}
}
We use the Try Catch block in a similar way you have suggested and it works well for us.
We have implemented ELMAH https://code.google.com/p/elmah/ which is great for logging untrapped errors. With a line of code in the Try Catch block you can also write trapped exceptions into the log.
Catch ex As Exception
Elmah.ErrorSignal.FromCurrentContext.Raise(ex)
Return False
End Try
The error is handled (the relevant function returned false) and user doesn’t get the Yellow Screen of Death, and we can look up full details of any errors in the log.

adding a try catch around a large method call

I have a web service that's pretty simple; something like this:
public class LeadService : System.Web.Services.WebService {
[WebMethod(EnableSession = true)]
public string MyService(string TheIncomingData)
{
string ReturnData = "";
MyClass TheClass = new MyClass();
ReturnData = TheClass.MyMethod(TheIncomingData);
return ReturnData;
}
}
You might have guessed it, the MyMethod is a pretty long-running method with some room for errors (for now). If I add a try/catch statement around the method call like this:
try { ReturnData = TheClass.MyMethod(TheIncomingData); }
catch { ReturnData = ""; }
Is this going to make the service and the app exception-proof? And, is using a try statement like this going to have any performance impact even if no error occurs?
Thanks for your advice.
Is using a try statement like this going to have any performance impact even if no error occurs?
No.
Is the application exception-proof?
Yes. However if you have onApplicationError event in the Global.asax you won't be able to see the error since you are not throwing a new one.
But the way I see it for now, your code is safe from exceptions.
Is this going to make the service and the app exception-proof?
Yes, it seems that's the only place where exception can raise. So you will catch every exception using this try catch
And, is using a try statement like this going to have any performance impact even if no error occurs?
No, it won't cause any performance issue in case of no error
On the side note it is not a good practise to just ignore the exception like this. May be you can return a customized error to user so that user can do something instead of just wondering why I am getting back a empty string
That's a way to make the app "exception-proof", yes, at least when seen by a client. But it won't make it error-proof, and it will make it harder to find an error whenever your client gets an empty string.
If you are willing to accept the risk of swallowing exceptions and potentially leaving your application in an undefined state, you could at least return the exception info as the result so that someone can understand what really happened. If there was an unanticipated input, you must inform your clients and log the error for yourself.
Did your client enter invalid input data? Do you know which data it was, and how to repeat the problem?
Did it happen with valid data? Where and how did it happen?
A much better solution would be to add the Application_Error handler method in your Global.ashx file, log the exception (possibly notifying the admin by e-mail when this happens), and use a custom error page for your users.
This article explains it well: Global Error Handling in ASP.NET.
Is it exception proof? Yes. Will it hurt performance? Not as far as the execution of this code block is concerned. However, I suggest you rewrite the code so that it allows you to handle the exception and get the desired result:
public class LeadService : System.Web.Services.WebService {
[WebMethod(EnableSession = true)]
public string MyService(string TheIncomingData)
{
MyClass TheClass = new MyClass();
try{
return TheClass.MyMethod(TheIncomingData);
}
catch(Exception ex){
//handle your exception, log, etc.
}
return "";
}
}

Try/Catch block not catching Exception

I have a statement inside a try/catch block, but the exception is not getting caught. Can anyone explain?
Exception Details:
System.NullReferenceException: Object
reference not set to an instance of an
object.
Source Error:
Line 139: try
Line 140: {
Line 141: return (int)Session["SelectedLeadID"];
Line 142: }
Line 143: catch (Exception ex)
Update
This is an ASP.NET application. In the catch block, a new exception is thrown. The code you see is what is displayed on the ASP.NET error page.
That catch block should catch the exception, but make sure there's no re-throwing in there.
Another small comment: I've been tricked quite a few times by VS, cause it breaks on exceptions like that while running in debug-mode. Try to simply press 'continue' or 'F5' and see if your application doesn't work anyway :)
I suspect you're going to need to add more detail - that isn't reproducible just from your code. In particular (as already noted) we'd need to see inside the catch, and verify that the exception is actually being thrown from inside the try and not somewhere else.
Other possibilities:
you have dodgy code inside the exception handler that is itself throwing an exception
you have a dodgy Dispose() that is getting called (using etc)
you are in .NET 1.1 and the thing getting thrown (in code not shown) isn't an Exception, but some other object
If it is only the debugger breaking on the exception and you are using VS2005 or above, you might want to check under Debug->Exceptions... if any of the Common-Language-Runtime-Exceptions are activated. If so, the debugger will always catch the exceptions first, but you are allowed to continue.
To revert to normal execution, simply uncheck the apropriate exceptions from the list.
I also faced this problem
Image
which was solved by removing the tick of
"Break when this exception type is thrown."
Warning:
Of course, I am not aware of the consequences of this.
I've also had such an issue and it was driving me nuts for quite some time, but in the end I figured it out. It's quite stupid, but maybe it might help someone:
public IActionResult SomeFunction()
{
try
{
return Json(new ClassWhichTakes2Parameters("FirstParameter"), "SecondParameter"); //comma placed in the wrong spot
}
catch (Exception ex)
{
//some code
}
}
It should have looked like:
public IActionResult SomeFunction()
{
try
{
return Json(new ClassWhichTakes2Parameters("FirstParameter", "SecondParameter"));
}
catch (Exception ex)
{
//some code
}
}
Since I had many return statements in that function I didn't catch this right away.
Also, the error message I've been receiving wasn't quite what I have expected at first, but now it makes sense:
System.InvalidOperationException: Property
'JsonResult.SerializerSettings' must be an instance of type
'Newtonsoft.Json.JsonSerializerSettings'.
The code looks terribly ugly IMO. For there to be something in the catch() block means you are going to have another return ... statement which AFAIK you should always have a single return statement at the end of each function to make following code easier.
i.e. maybe your code should look like
public int Function()
{
int leadID = 0;
try
{
int leadID = (int)Session["SelectedLeadID"];
}
catch (Exception ex)
{
...
}
return leadID
}
Single exit points are supposed to make the code easier to follow, I guess? Anyway, to get any useful help you have to post more of the function.

What's a good way for a c# dll to return error to the calling application?

i'm writing a dll which is a wrapper to a access database. and i'm pretty new to c# in general as my background is in web development LAMP with perl, i'm not sure what's a good way to return error to a calling app in case they pass the wrong parameters to my functions or what not.
I have no idea as of now except to probably do some msgbox or throw some exceptions but i don't know where to start looking. Any help or resources would be more than useful :)
thanks~
You probably don't want to display message dialogs from within your dll, that's the job of the client application, as part of the presentation layer.
.Net library assemblies typically bubble up exceptions to the host application, so that's the approach I'd look at.
public static class LibraryClass
{
public static void DoSomething(int positiveInteger)
{
if (positiveInteger < 0)
{
throw new ArgumentException("Expected a positive number", "positiveInteger");
}
}
}
Then it's up to your host application to handle those exceptions, logging and displaying them as appropriate.
try
{
LibraryClass.DoSomething(-3);
}
catch(ArgumentException argExc)
{
MessageBox.Show("An Error occurred: " + argExc.ToString());
}
Wrong parameters are usually handled by throwing a ArgumentException or one of its subclasses.
You want to throw an exception.
See
http://msdn.microsoft.com/en-us/library/ms229007.aspx
for the most common framework exceptions, such as ArgumentException and InvalidOperationException. See also
http://msdn.microsoft.com/en-us/library/ms229030.aspx
Check out Design Guidelines for Class Library Developers: Error Raising and Handling Guidelines
Dlls generally should not create any kind of UI element to report an error. You can Throw (same meaning as raise) many different kinds of exceptions, or create your own and the calling code (client) can catch and report to the user.
public void MyDLLFunction()
{
try
{
//some interesting code that may
//cause an error here
}
catch (Exception ex)
{
// do some logging, handle the error etc.
// if you can't handle the error then throw to
// the calling code
throw;
//not throw ex; - that resets the call stack
}
}
throw new exception?

Is a finally block without a catch block a java anti-pattern?

I just had a pretty painful troubleshooting experience in troubleshooting some code that looked like this:
try {
doSomeStuff()
doMore()
} finally {
doSomeOtherStuff()
}
The problem was difficult to troubleshoot because doSomeStuff() threw an exception, which in turn caused doSomeOtherStuff() to also throw an exception. The second exception (thrown by the finally block) was thrown up to my code, but it did not have a handle on the first exception (thrown from doSomeStuff()), which was the real root-cause of the problem.
If the code had said this instead, the problem would have been readily apparent:
try {
doSomeStuff()
doMore()
} catch (Exception e) {
log.error(e);
} finally {
doSomeOtherStuff()
}
So, my question is this:
Is a finally block used without any catch block a well-known java anti-pattern? (It certainly seems to be a not-readily-apparent subclass of the obviously well-known anti-pattern "Don't gobble exceptions!")
In general, no, this is not an anti-pattern. The point of finally blocks is to make sure stuff gets cleaned up whether an exception is thrown or not. The whole point of exception handling is that, if you can't deal with it, you let it bubble up to someone who can, through the relatively clean out-of-band signaling exception handling provides. If you need to make sure stuff gets cleaned up if an exception is thrown, but can't properly handle the exception in the current scope, then this is exactly the correct thing to do. You just might want to be a little more careful about making sure your finally block doesn't throw.
I think the real "anti-pattern" here is doing something in a finally block that can throw, not not having a catch.
Not at all.
What's wrong is the code inside the finally.
Remember that finally will always get executed, and is just risky ( as you have just witnessed ) to put something that may throw an exception there.
There is absolutely nothing wrong a try with a finally and no catch. Consider the following:
InputStream in = null;
try {
in = new FileInputStream("file.txt");
// Do something that causes an IOException to be thrown
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// Nothing we can do.
}
}
}
If an exception is thrown and this code doesn't know how to deal with it then the exception should bubble up the call stack to the caller. In this case we still want to clean up the stream so I think it makes perfect sense to have a try block without a catch.
I think it's far from being an anti-pattern and is something I do very frequently when it's critical do deallocate resources obtained during the method execution.
One thing I do when dealing with file handles (for writing) is flushing the stream before closing it using the IOUtils.closeQuietly method, which doesn't throw exceptions:
OutputStream os = null;
OutputStreamWriter wos = null;
try {
os = new FileOutputStream(...);
wos = new OutputStreamWriter(os);
// Lots of code
wos.flush();
os.flush();
finally {
IOUtils.closeQuietly(wos);
IOUtils.closeQuietly(os);
}
I like doing it that way for the following reasons:
It's not completely safe to ignore an exception when closing a file - if there are bytes that were not written to the file yet, then the file may not be in the state the caller would expect;
So, if an exception is raised during the flush() method, it will be propagated to the caller but I still will make sure all the files are closed. The method IOUtils.closeQuietly(...) is less verbose then the corresponding try ... catch ... ignore me block;
If using multiple output streams the order for the flush() method is important. The streams that were created by passing other streams as constructors should be flushed first. The same thing is valid for the close() method, but the flush() is more clear in my opinion.
I'd say a try block without a catch block is an anti-pattern. Saying "Don't have a finally without a catch" is a subset of "Don't have a try without a catch".
I use try/finally in the following form :
try{
Connection connection = ConnectionManager.openConnection();
try{
//work with the connection;
}finally{
if(connection != null){
connection.close();
}
}
}catch(ConnectionException connectionException){
//handle connection exception;
}
I prefer this to the try/catch/finally (+ nested try/catch in the finally).
I think that it is more concise and I don't duplicate the catch(Exception).
try {
doSomeStuff()
doMore()
} catch (Exception e) {
log.error(e);
} finally {
doSomeOtherStuff()
}
Don't do that either... you just hid more bugs (well not exactly hid them... but made it harder to deal with them. When you catch Exception you are also catching any sort of RuntimeException (like NullPointer and ArrayIndexOutOfBounds).
In general, catch the exceptions you have to catch (checked exceptions) and deal with the others at testing time. RuntimeExceptions are designed to be used for programmer errors - and programmer errors are things that should not happen in a properly debugged program.
In my opinion, it's more the case that finally with a catch indicate some kind of problem. The resource idiom is very simple:
acquire
try {
use
} finally {
release
}
In Java you can have an exception from pretty much anywhere. Often the acquire throws a checked exception, the sensible way to handle that is to put a catch around the how lot. Don't try some hideous null checking.
If you were going to be really anal you should note that there are implied priorities among exceptions. For instance ThreadDeath should clobber all, whether it comes from acquire/use/release. Handling these priorities correctly is unsightly.
Therefore, abstract your resource handling away with the Execute Around idiom.
Try/Finally is a way to properly free resources. The code in the finally block should NEVER throw since it should only act on resources or state that was acquired PRIOR to entry into the try block.
As an aside, I think log4J is almost an anti-pattern.
IF YOU WANT TO INSPECT A RUNNING PROGRAM USE A PROPER INSPECTION TOOL (i.e. a debugger, IDE, or in an extreme sense a byte code weaver but DO NOT PUT LOGGING STATEMENTS IN EVERY FEW LINES!).
In the two examples you present the first one looks correct. The second one includes the logger code and introduces a bug. In the second example you suppress an exception if one is thrown by the first two statements (i.e. you catch it and log it but do not rethrow. This is something I find very common in log4j usage and is a real problem of application design. Basically with your change you make the program fail in an way that would be very hard for the system to handle since you basically march onward as if you never had an exception (sorta like VB basic on error resume next construct).
try-finally may help you to reduce copy-paste code in case a method has multiple return statements. Consider the following example (Android Java):
boolean doSomethingIfTableNotEmpty(SQLiteDatabase db) {
Cursor cursor = db.rawQuery("SELECT * FROM table", null);
if (cursor != null) {
try {
if (cursor.getCount() == 0) {
return false;
}
} finally {
// this will get executed even if return was executed above
cursor.close();
}
}
// database had rows, so do something...
return true;
}
If there was no finally clause, you might have to write cursor.close() twice: just before return false and also after the surrounding if clause.
I think that try with no catch is anti-pattern. Using try/catch to handle exceptional conditions (file IO errors, socket timeout, etc) is not an anti-pattern.
If you're using try/finally for cleanup, consider a using block instead.

Categories