try
{
using (response = (HttpWebResponse)request.GetResponse())
// Exception is not caught by outer try!
}
catch (Exception ex)
{
// Log
}
EDIT:
// Code for binding IP address:
ServicePoint servicePoint = ServicePointManager.FindServicePoint(uri);
servicePoint.BindIPEndPointDelegate = new BindIPEndPoint(Bind);
//
private IPEndPoint Bind(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
{
IPAddress address;
if (retryCount < 3)
address = IPAddress.Parse("IPAddressHere");
else
{
address = IPAddress.Any;
throw new Exception("IP is not available,"); // This exception is not caught
}
return new IPEndPoint(address, 0);
}
I could imagine this can happen if you are creating a separate thread within the using block. If an exception is thrown there, be sure to handle it there as well. Otherwise, the outer catch block in this case won't be able to handle it.
class TestClass : IDisposable
{
public void GetTest()
{
throw new Exception("Something bad happened"); // handle this
}
public void Dispose()
{
}
}
class Program
{
static void Main(string[] args)
{
try
{
using (TestClass t = new TestClass())
{
Thread ts = new Thread(new ThreadStart(t.GetTest));
ts.Start();
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
Do you have more code after the using? The using needs one statement or a block { } after the using statement. In the example below any exception inside the using statement will be caught with the try..catch block.
try
{
using (response = (HttpWebResponse)request.GetResponse())
{
....
}
}
catch (Exception ex)
{
}
This works fine. You'll see an exception getting printed by the Console.WriteLine()
class Program
{
static void Main(string[] args)
{
Foo foo = new Foo();
try
{
using (Bar bar = foo.CreateBar())
{
}
}
catch(Exception exception)
{
Console.WriteLine(exception.Message);
}
}
}
public class Foo
{
public Bar CreateBar()
{
throw new ApplicationException("Something went wrong.");
}
}
public class Bar : IDisposable
{
public void Dispose()
{
}
}
And if you meant that the exception gets thrown inside the using, this works fine to. This will also generate a Console statement:
class Program
{
static void Main(string[] args)
{
Foo foo = new Foo();
try
{
using (Bar bar = foo.CreateBar())
{
throw new ApplicationException("Something wrong inside the using.");
}
}
catch(Exception exception)
{
Console.WriteLine(exception.Message);
}
}
}
public class Foo
{
public Bar CreateBar()
{
return new Bar();
// throw new ApplicationException("Something went wrong.");
}
}
public class Bar : IDisposable
{
public void Dispose()
{
}
}
The using keyword is the same as try-catch-finally, http://msdn.microsoft.com/en-us/library/yh598w02.aspx. Basically, you have a try-catch-finally nested inside of a try-catch which is why you're probably so confused.
You could just do this instead...
class Program
{
static void Main(string[] args)
{
HttpWebResponse response = new HttpWebResponse();
try
{
response.GetResponse();
}
catch (Exception ex)
{
//do something with the exception
}
finally
{
response.Dispose();
}
}
}
Related
using System;
// Custom Exception types
class AException : Exception
{
}
class BException : Exception
{
}
class Test
{
public static void Main(string[] args)
{
try
{
throw new AException();
}
catch (Exception ex)
{
Callme(ex);
}
}
public static void Callme(AException aexception) {}
public static void Callme(BException bexception) {}
public static void Callme(Exception ex) {}
}
Callme(ex) will always call Callme(Exception ex) instead of Callme(AException ..) .. Is this an expected behavior. I read method overload resolution do work with inheritance relationships.
there is a more accepted way of doing this. try the following:
try
{
throw new AException();
}
catch (AException aex)
{
Callme(aex);
}
catch (BException bex)
{
Callme(bex);
}
catch (Exception ex)
{
Callme(ex);
}
I use Activator.CreateInstance to instantiate dynamic class, my class constructor generate Exception if issue appears.
When I use the parameterless constructor (Test 1), I can catch the exception launch by the instantiated class around the CreateInstance.
But, if I use constructor with argument, the exception is not catch by the try catch around the CreateInstance.
How I can catch this exception ?
using System;
using System.Text;
namespace ConsoleApplication1
{
public abstract class Base
{
public Base()
{
throw new Exception(" -= TEST = Bad filename. =- ");
}
public Base( String filename)
{
throw new Exception(" -= TEST = Bad filename. =- ");
}
}
public class Child : Base
{
public Child()
: base()
{
}
public Child(String filename)
: base(filename)
{
}
}
class Program
{
static void Main(string[] args)
{
try
{
Base child = (Base)Activator.CreateInstance(typeof(Child));
}
catch (Exception e)
{
Console.WriteLine("Test 1 (no argument): Catch OK");
Console.WriteLine(e.ToString());
}
Console.WriteLine("Test 1: OK\n--------------------------");
Console.ReadKey();
try
{
Base child = (Base)Activator.CreateInstance(typeof(Child), "foo");
}
catch (Exception e)
{
Console.WriteLine("Test 2 (with argument): Catch OK");
Console.WriteLine(e.ToString());
}
Console.WriteLine("The end");
Console.ReadKey();
}
}
}
Here is a sample C++ macro that I use to make my code more readable and reduce the Try-Catch Clutter:
#define STDTRYCATCH(expr) \
try { \
return (expr); \
} \
catch (const std::exception& ex) { \
handleException(ex); \
} \
catch (...) { \
handleException(); \
}
Which can be used as:
int myClass::Xyz()
{
STDTRYCATCH(myObj.ReadFromDB());
}
Please note that I'm looking for STDTRYCATCH that handles any code stub we enclose with it.Is there an equivalent in C# ?
You can write helper:
public static class ExcetpionHandler
{
public static void StdTryCatch(this object instance, Action act)
{
try
{
act();
}
catch (Exception ex)
{
var method = instance.GetType().GetMethod("StdException");
if (method != null)
{
method.Invoke(instance, new object[] {ex});
}
else
{
throw;
}
}
}
}
Usage:
public class MyClass
{
public void StdException(Exception ex)
{
Console.WriteLine("Thrown");
}
public void Do()
{
this.StdTryCatch(() =>
{
throw new Exception();
});
}
}
and:
class Program
{
static void Main(string[] args)
{
var instance = new MyClass();
instance.Do();
}
}
But it is not recommeded - due to performance reasons etc - like mentioned in comments.
EDIT:
Like cdhowie mentioned, you can also prepare inteface:
public interface IExceptionHandler
{
void StdException(Exception ex);
}
Then:
public static class ExcetpionHandler
{
public static void StdTryCatch(this IExceptionHandler instance, Action act)
{
try
{
act();
}
catch (Exception ex)
{
instance.StdException(ex);
}
}
}
Your class then need to impelement that interface.
So I have the following block of code inside a method: (all variables are local)
// ...
try
{
if (postXml != null)
using (StreamWriter writer = new StreamWriter(req.GetRequestStream()))
writer.Write(postXml.ToString());
}
catch (WebException ex)
{
HttpWebResponse response = ex.Response as HttpWebResponse;
if (response != null)
result = HandleOtherResponse(response, out status);
else result = HandleBadResponse(ex.ToString(), out status);
}
catch (Exception ex)
{
result = HandleBadResponse(ex.ToString(), out status);
}
if (result == null)
{
try
{
HttpWebResponse response = req.GetResponse() as HttpWebResponse;
result = HandleOtherResponse(response, out status);
}
catch (WebException ex)
{
HttpWebResponse response = ex.Response as HttpWebResponse;
if (response != null)
result = HandleOtherResponse(response, out status);
else result = HandleBadResponse(ex.ToString(), out status);
}
catch (Exception ex)
{
result = HandleBadResponse(ex.ToString(), out status);
}
}
// ...
As you can see, the two try statements are different, but the two sets of catch statements are exactly the same. I've been trying to think of a way that it might be possible to not repeat myself here, but I haven't really thought of a way that wouldn't be significantly slower or just as terrible looking. Wondering if anyone has any ideas.
One way would be to write a "safe" invocation method and pass a func to it:
public T SafeInvocation(Func<T> myMethod)
{
T result = default(T);
try
{
// Invoke method
result = myMethod();
}
catch
{
// Do your common catch here
}
return result;
}
Build an additional overload for Action<T> so that you don't need to have a return type. Then you could invoke it elsewhere, passing methods to your method as arguments (Inception?):
SafeInvocation(() =>
{
if (postXml != null)
using (StreamWriter writer = new StreamWriter(req.GetRequestStream()))
writer.Write(postXml.ToString());
}
You could pass an Action into a function that handles the exceptions:
private void HandleErrorsFor(Action action)
{
try
{
action();
}
catch (Exception ex)
{
//repeated exception handling...
{
}
//...
public void DoSomething()
{
HandleErrorsFor(() => {
//try block #1
});
HandleErrorsFor(() => {
//try block #2
});
}
It's a bit easier to read and avoids the repeated code.
You can do something with delegates and cover both try and catch blocks:
static class Program
{
delegate void CodeBlock();
internal delegate void ExceptionCatcher(Exception ex);
private static void Main()
{
CodeBlock b = () => { Console.WriteLine("HELLO WORLD"); };
CodeBlock error = () => { throw new Exception("Exception thrown"); };
ExceptionCatcher silence = exception => { };
ExceptionCatcher e = exception =>
{
var currentColor = Console.BackgroundColor;
Console.BackgroundColor = ConsoleColor.Red;
Console.WriteLine(exception.Message);
Console.BackgroundColor = currentColor;
};
DRYRunner(b, e);
DRYRunner(error , e);
DRYRunner(error , silence);
Console.ReadLine();
}
static void DRYRunner (CodeBlock block, ExceptionCatcher catcher)
{
try
{
block.Invoke();
}
catch (Exception ex)
{
catcher(ex);
}
}
}
edit: Extending this out, we can create a class to help contain and associate code blocks with their possible exceptions and handlers. You could even create a class of common exception handlers and reference them accordingly, mixing them in with ad-hoc handlers:
class ExceptionHandledDelegate
{
public delegate void CodeBlock();
public delegate void ExceptionCatcher(Exception ex);
public Dictionary<Type, ExceptionCatcher> ExceptionHandlers;
public CodeBlock codeBlock { get; set; }
public void Run()
{
try
{
codeBlock.Invoke();
}
catch (Exception ex)
{
var mn = ex.GetType();
if (ExceptionHandlers.Keys.Contains(mn))
{
ExceptionHandlers[mn](ex);
}
else throw;
}
}
}
class CommonHandlers
{
public static void ArgumentHandler(Exception ex)
{
Console.WriteLine("Handling an argument exception");
}
public static void DivZeroHandler(Exception ex)
{
Console.WriteLine("Please don't divide by zero. It upsets the universe.");
}
}
static class Program
{
private static void Main()
{
var ehd = new ExceptionHandledDelegate
{
codeBlock = () => { throw new ArgumentException("An argument exception has been thrown"); },
ExceptionHandlers = new Dictionary<Type, ExceptionHandledDelegate.ExceptionCatcher>
{
{typeof (ArgumentException), CommonHandlers.ArgumentHandler},
{typeof (DivideByZeroException ),CommonHandlers.DivZeroHandler},
{typeof (Exception), exception => Console.WriteLine("An exception has been thrown")}
}
};
ehd.Run();
ehd.codeBlock = () => { throw new Exception("An exception has been thrown"); };
ehd.Run();
ehd.codeBlock = () =>{var denom = 0; Console.WriteLine(100 / denom);};
ehd.Run();
Console.ReadLine();
}
}
I'm not exactly sure how to address this issue. I have a mutex that is declared as such:
public class MyNamedLock
{
private Mutex mtx;
private string _strLkName;
public MyNamedLock(string strLockName)
{
_strLkName = strLockName;
//...
mtx = new Mutex(false, _strLkName, out bCreatedNew, mSec);
}
public bool enterLockWithTimeout(int nmsWait = 30 * 1000)
{
_nmsWaitLock = nmsWait;
//Wait
return mtx.WaitOne(nmsWait);
}
public void leaveLock()
{
_nmsWaitLock = 0;
//Release it
mtx.ReleaseMutex();
}
}
Then it is used in an ASP.NET page as such:
public class MyClass
{
private MyNamedLock gl;
public MyClass()
{
gl = new MyNamedLock("lock name");
}
public void funct()
{
try
{
//Enter lock
if (gl.enterLockWithTimeout())
{
//Do work
}
else
throw new Exception("Failed to enter lock");
}
finally
{
//Leave lock
gl.leaveLock();
}
}
}
This code doesn't give me any trouble in my dev environment but in the production it sometimes throws this exception:
Object synchronization method was called from an unsynchronized block
of code.
The description is kinda vague, but just doing the trace I found out that the exception is raised at the mtx.ReleaseMutex(); part. What does it mean and how to fix it?
You have some issues on your class, and on the way you use it.
You must release the mutex only if you have previous locked (and this is your error)
You need to Close and Dispose your opened mutex
Also is better to create it just before you going to use it and not when you create you class MyClass.
So I suggest at first look to change your class as:
public class MyNamedLock
{
private Mutex mtx = null;
private string _strLkName;
// to know if finally we get lock
bool cNeedToBeRelease = false;
public MyNamedLock(string strLockName)
{
_strLkName = strLockName;
//...
mtx = new Mutex(false, _strLkName, out bCreatedNew, mSec);
}
public bool enterLockWithTimeout(int nmsWait = 30 * 1000)
{
_nmsWaitLock = nmsWait;
bool cLock = false;
try
{
cLock = mtx.WaitOne(nmsWait, false);
cNeedToBeRelease = cLock;
}
catch (AbandonedMutexException)
{
// http://stackoverflow.com/questions/654166/wanted-cross-process-synch-that-doesnt-suffer-from-abandonedmutexexception
// http://msdn.microsoft.com/en-us/library/system.threading.abandonedmutexexception.aspx
cNeedToBeRelease = true;
}
catch (Exception x)
{
// log the error
Debug.Fail("Check the reason of fail:" + x.ToString());
}
return cLock;
}
public void leaveLock()
{
_nmsWaitLock = 0;
if (mtx != null)
{
if (cNeedToBeRelease)
{
try
{
mtx.ReleaseMutex();
cNeedToBeRelease = false;
}
catch (Exception x)
{
Debug.Fail("Check the reason of fail:" + x.ToString());
}
}
mtx.Close();
mtx.Dispose();
mtx = null;
}
}
}
This the way you must call that class:
public class MyClass
{
public MyClass()
{
}
public void funct()
{
var gl = new MyNamedLock("lock name");
try
{
//Enter lock
if (gl.enterLockWithTimeout())
{
//Do work
}
else
throw new Exception("Failed to enter lock");
}
finally
{
//Leave lock
gl.leaveLock();
}
}
}
In your finally block you're releasing the mutex regardless of whether you actually acquired it in your try block.
In
try
{
//Enter lock
if (gl.enterLockWithTimeout())
{
//Do work
}
else throw new Exception("Failed to enter lock");
}
finally
{
//Leave lock
gl.leaveLock();
}
if gl.enterLockWithTimeout returns false, you will throw an exception but then try to release the lock in the finally block.