开发者

Try Catch Not Working on BadImageFormatException

开发者 https://www.devze.com 2023-03-10 23:54 出处:网络
I have a MVC 开发者_运维知识库app that is loading a external DLL and when in production I get no error at all.Firefox just says the connection was reset.So I put some try/catch in the code but they st

I have a MVC 开发者_运维知识库app that is loading a external DLL and when in production I get no error at all. Firefox just says the connection was reset. So I put some try/catch in the code but they still do not work, I still get the connection reset message.

I know the error is a BadImageFormatException but why don't I see anything in the browser?

 public class HomeController : Controller
    {

        [DllImport("CDCrypt.dll")]
        [return: MarshalAs(UnmanagedType.LPStr)]
        public static extern String Encrypt([MarshalAs(UnmanagedType.LPStr)] String aName);



        [DllImport("CDCrypt.dll")]
        [return: MarshalAs(UnmanagedType.LPStr)]
        public static extern String Decrypt([MarshalAs(UnmanagedType.LPStr)] String aName);


        //
        // GET: /Home/

        public ActionResult Index()
        {

            try
            {
                ViewBag.EncryptString = Encrypt("test");
            }
            catch (Exception e)
            {
                ViewBag.EncryptString = "Stack Trace\r\n:" + "\r\nException: " + e.Message;
                return new HttpStatusCodeResult(500);
            }
            return View();
        }

        public ActionResult Up()
        {
            ViewBag.Up = "You can see me";
            return View();
        }



    }


There seem to be some exceptions which are marked as unrecoverable and so cannot be caught. This question (well this answer really) has a list of them, but I don't know how exhaustive this is.

This article has some more information about uncatchable exceptions, and how they can be caught if you throw them but not if the runtime throws them.

This question says that doing a catch rather than a catch(Exception ex) will allow COM exceptions to be caught as well. Don't know if this will help (I doubt it) but is interesting, and might.


http://msdn.microsoft.com/en-us/library/system.badimageformatexception.aspx

The exception that is thrown when the file image of a dynamic link library (DLL) or an executable program is invalid.

I will put this crudely - your program itself is not able to run, so there is no point in having the Try-Catch.

COM methods report errors by returning HRESULTs; .NET methods report them by throwing exceptions. The runtime handles the transition between the two.

Have a look here for some not so crude explanation on how to map HRESULTs and Exceptions: http://msdn.microsoft.com/en-us/library/9ztbc5s1.aspx

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号