How to catch exceptions in initialization section of Units in Delphi - delphi

I have a third party unit, witch raises an exception in initialization section of unit. How can I catch this exception on my application?

You cannot catch such a thing. The RTL executes the initialization sections and the rules are that no exceptions are to be raised. If exceptions are raised, then the fault is terminal.
Another way to thing about this is that when the initialization sections start to be executed, the language exception handling framework is not yet in place. That itself is installed as part of the RTL initialization.
The solution is to fix the code so that it obeys the rules. No exceptions raised in initialization sections.
Well, I suppose that you could hook the RTL code that executes initialization and perhaps replace that RTL code with exception resilient code. But what would be the point? If an initialization section raises an exception, the only sane assumption to be made is that the unit is not initialized and so not fit for use. Please don't try to bury your head in the sand and ignore the real problem. Fix the third party code.

You could try the OnExceptionEvent of the class TApplicationEvents, but I'm not sure if this works.

Related

Transitioning from VB6 On Error to .Net Try...Catch

Our company has recently transitioned from VB6 to VB.NET. Unfortunately all the error handling remains as On Error GoTo. This has not made it easy to track down errors that customers send back to tech support. As of now, the blocks of code that the On Error surrounds is entire subroutines, not uncommonly hundreds of lines of code for one sub, and possibly making calls to other routines. My question is how to best go about converting to Try...Catch blocks. I assume I can just substitute On Error GoTo Errorline for try and Errorline for catch. But this seems like too much for one try...catch block to encompass.
VB6's big weakness with error-handling is that the runtime does not provide a way for your code to get at the execution stack (method A called method B called method C, etc.) when an exception occurs; even if your On Error block catches the exception, you code doesn't know "where it is". To get around that deficiency, VB6 programmers have learned to enclose every method, in every module, with a catch-all On Error block, sometimes so that their own code can keep track of the execution stack for logging purposes. There were even third-party tools that could be used to instrument your code with On Error blocks, for exactly that purpose (VB/Rig, VB-Failsafe).
.Net's Exception object, however, does provide a .StackTrack property that represents the execution stack to the point of failure, so it's no longer necessary to use On Error blocks in every method, just so you can learn where your code failed, post-mortem.
Here is one simple strategy you can use, as you transition:
First, as you suggested, replace all of your "boilerplate" On Error Goto Errorline / :Errorline with Try / Catch ex As Exception blocks. But, do this only in the "top-level" methods where execution can "begin". In VB, these are usually all of the Event methods in your forms that directly handle system events (_Click, _MouseDown, _Timer, etc.)
Second, remove all the boilerplate error handling from "lower-level" methods -- methods that are merely called from the "top-level" or other "lower-level" methods.
Now you have provided a "safety net" of Try/Catch exception handling that will protect your app from dying from an unhandled exception. When an exception does occur, even deep in the execution stack, your code will unwind back to the nearest Catch, usually one of your UI event-handler methods. But, you will have the ex.StackTrack property that documents the execution up to the failure, module by module, method by method, with the source code line-number at each level.
One exception to the above strategy is when you find an error-handling block that is not boilerplate -- it was written specifically to handle a certain error(s), and to respond specifically. Leave this code in place, but again replace the On Error Goto Errorline / :Errorline with Try / Catch ex As Exception.
Here's a helpful rule of thumb: In your "top-level" methods, enclose the entire method in a "boilerplate" Try/Catch. In your "lower-level" methods, only write Try/Catch blocks around code where you can anticipate that certain exceptions will occur -- ones that your code wants to specifically respond to.
It's not unreasonable, or "too much", for a Try/Catch block to encompass large chunks of code. You should always strive to keep your methods as short as possible, but there is no reason to arbitrarily truncate or partition a long method just because it's enclosed by a Try/Catch.

Creating NonContinuable exception in delphi

I have an exception which its raise command causes stack overflow. I read this article in order to know what should I do: http://www.debuggingexperts.com/modeling-exception-handling
What I understood is the exception 0xc0000025 means attempt to catch an exception which is forbidden to be caught (EXCEPTION_NONCONTINUABLE_EXCEPTION). Am I right?
If so, I wish to know what cause the exception to be defined as non-continuable. The exception is defined in Pascal and derived from Exception object.
In addition, I failed to found where this exception is handled, and added by myself a try-catch block. The exception caught successfully. Why?
EDIT
I want to explain the specific situation I need help:
There is a C++ code which calls Pascal code, which has the exception definition, and raise command happens in it.
Before I put the try-catch block in the C++ code, the raise in Pascal causes 1000 times exception of EXCEPTION_NONCONTINUABLE_EXCEPTION until stack overflowed.
After I added the try-catch block in the C++ code, the raise in Pascal code returned to the catch block in the C++ code.
Now I have 2 questions:
Why process didn't stop on the first NONCONTINUABLE exception?
Why the catch block in C++ code didn't cause this exception?
You are correct that EXCEPTION_NONCONTINUABLE_EXCEPTION means the program attempted to continue from an exception that isn't continuable. However, it's not possible to define such an exception in Delphi, so the source of your problem is elsewhere.
Consider debugging the creation, raising, catching, and destruction of your custom exception type. If there are external libraries involved in your program, particularly any written in something other than Delphi, make sure they either know what to do with external exceptions, or are shielded entirely from exceptions.

Where to place exception loggging in ASP.NET MVC

Can anyone please explain difference between below two approaches.
Logging in controller's OnException event:
try
{
//code
}
catch
{
//rollback trasanctions
throw;
}
Or, logging in catch block:
try
{
//code
}
catch
{
//logging here
//rollback trasactions
throw;
}
The Controller's OnException method is used when an unhandled exception occurs in the processing of the request. It is indicates what functionality should happen if an unexpected exception occurs. You should really only use this as a safeguard in the event that you messed up or the system failed in an unexpected, fatal way.
If you are executing some piece of code that you expect to throw a specific exception, wrap it in try block, and handle the specific exception accordingly. This defensive approach will help you debug issues as soon as they happen, rather than wait for them to bubble up to a point where you don't know the cause.
Think about it, if you have multiple action methods and only one OnException method per controller, then you have a much more complex issue to handle, because any of the action methods or filters could have thrown the error. However, if you catch an exception called by a specific service call then you already know exactly what caused the unexpected behavior, and it will be much easier to address accordingly.
Read this for greater understanding: Eric Lippert has an excellent article in which he breaks down the different categories of exceptions that we encounter and offers best practices for addressing them. It is available at http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx . In case you don't know who Eric Lippert is, he is very smart and you should listen to him if you code in C#. His main points are:
Don’t catch fatal exceptions; nothing you can do about them anyway, and trying to generally makes it worse.
Fix your code so that it never triggers a boneheaded exception – an "index out of range" exception should never happen in production code.
Avoid vexing exceptions whenever possible by calling the “Try” versions of those vexing methods that throw in non-exceptional circumstances. If you cannot avoid calling a vexing method, catch its vexing exceptions.
Always handle exceptions that indicate unexpected exogenous conditions; generally it is not worthwhile or practical to anticipate every possible failure. Just try the operation and be prepared to handle the exception.
Update
Just realized I didn't explicitly address the "logging" question. It probably makes most sense to avoid handling your fatal/exogenous errors in a controller scope, because you will end up duplicating your logic, often. This behavior is better handled in a global action filter.
This codeproject article Exception Handling in ASP.NET MVC explains how to override the default HandleErrorAttribute and leverage an ErrorController so that it can be applied globally.
In addition, the following 5-part blog series gives an in depth analysis of the different options you have for error handling in MVC applications: http://perspectivespace.com/error-handling-in-aspnet-mvc-3-index-of-posts

Exception thrown Constructor Injection - AutoFac Dependency Injection

I have an Autofac DI Container and use constructor injection to inject configuration settings into my SampleClass. The Configuration Manager class is created as a singleInstance so the same single instance is used.
public ConfigurationManager()
{
// Load the configuration settings
GetConfigurationSettings();
}
public SampleClass(IConfigurationManager configurationManager)
{
_configurationManager = configurationManager;
}
I am loading the configuration settings from a App.config file in the constructor of the configuration Manager. My problem is i am also validating the configuration settings and if they are not in the App.config file a exception is thrown, which causes the program to crash. Which means I cant handle the exception and return a response.
I am doing this the wrong way? Is there a better way to load the configuration settings Or is there a way to handle the exception being thrown.
Edit
ConfigurationManager configurationManager = new ConfigurationManager();
configurationManager.GetConfigurationSettings();
//Try catch around for the exception thrown if config settings fail
//Register the instance above with autofac
builder.Register(configurationManager()).As<IConfigurationManager>().SingleInstance();
//Old way of registering the configurationManager
builder.Register(c => new ConfigurationManager()).As<IConfigurationManager>().SingleInstance();
You are doing absolutely the right thing. Why? You are preventing the system from starting when the application isn't configured correctly. The last thing you want to happen is that the system actually starts and fails later on. Fail fast! However, make sure that this exception doesn't get lost. You could make sure the exception gets logged.
One note though. The general advice is to do as little as possible in the constructor of a type. Just store the incoming dependencies in instance variables and that's it. This way construction of a type is really fast and can never really fail. In general, building up the dependency graph should be quick and should not fail. In your case this would not really be a problem, since you want the system to fail as soon as possible (during start-up). Still, for the sake of complying to general advice, you might want to extract this validation process outside of that type. So instead of calling GetConfigurationSettings inside that constructor, call it directly from the composition root (the code where you wire up the container) and supply the valid configuration settings object to the constructor of the ConfigurationManager. This way you -not only- make the ConfigurationManager simpler, but you can let the system fail even faster.
The core issue is that you are mixing the composition and execution of your object graph by doing some execution during composition. In the DI style, constructors should be as simple as possible. When your class is asked to perform some meaningful work, such as when the GetConfigurationSettings method is called, that is your signal to begin in earnest.
The main benefit of structuring things in this way is that it makes everything more predictable. Errors during composition really are composition errors, and errors during execution really are execution errors.
The timing of work is also more predictable. I realize that application configuration doesn't really change during runtime, but let's say you had a class which reads a file. If you read it in the constructor during composition, the file's contents may change by the time you use that data during execution. However, if you read the file during execution, you are guaranteed to avoid the timing issues that inevitably arise with that form of caching.
If caching is a part of your algorithm, as I imagine it is for GetConfigurationSettings, it still makes sense to implement that as part of execution rather than composition. The cached values may not have the same lifetime as the ConfigurationManager instance. Even if they do, encoding that into the constructor leaves you only one option, where as an execution-time cache offers far more flexibility and it solves your exception ambuguity issue.
I would not call throwing exceptions at composition-time a good practice. It is so because composition might have a fairly complex and indirect execution logic making reasonable exception handling virtually impossible. I doubt you could invent anything better than awful
try
{
var someComponent = context.Resolve<SampleClass>();
}
catch
{
// Yeah, just stub all exceptions cause you have no idea of what to expect
}
I'd recommend redesigning your classes in a way that their constructors do not throw exceptions unless they do really really need to do that (e.g. if they are absolutely useless with a null-valued constructor parameter). Then you'll need some methods that initialize your app, handle errors and possibly interact with user to do that.

Guard page exceptions in Delphi?

There is a post by Raymond Chen, where he tells how bad IsBadXxxPtr function is by eating guard page exception.
I don't quite understand how it is applied to Delphi. Who and how should normally (i.e. without call to IsBadXxxPtr) process this exception?
I do know that Delphi inserts a code, which (for example) access a memory for large static arrays - exactly for this reason: to expand stack.
But if guard page exception is raised: who will handle it in a Delphi application? Can't I accidentally mess with it by using try/except in inappropriate way? Will Delphi's debugger notify me about these exceptions?
Windows structured exception handling (SEH) is has a two-phase structure. When an exception occurs, Windows first looks for a handler for the exception by following the registered exception handler chain (the head of which is stored in fs:[0] on x86, i.e. the first dword in the segment pointed to by the FS segment register - all that ugly 16-bit segment-offset logic didn't go away in 32-bit, it just became less relevant).
The search is done by calling a function with a particular flag, a pointer to which is stored in each exception frame on the stack. fs:[0] points to the topmost frame. Each frame points to the previous frame. Ultimately, the last frame on the list is one that has been provided by the OS (this handler will pop up a app-crash dialog if an unhandled exception reaches it).
These functions normally check the type of the exception, and return a code to indicate what to do. One of the codes that can be returned is basically, "ignore this exception and continue". If Windows sees this, it will reset the instruction pointer to the point of the exception and resume execution. Another code indicates that this exception frame should handle the given exception. A third code is "I'm not going to catch this exception, keep searching". Windows keeps on calling these exception filter functions until it finds one that handles the exception one way or the other.
If Windows finds one that handles the exception by catching it, then it will proceed to unwind the stack back to that handler, which consists of calling all the functions again, only passing in a different flag. It's at this point that the functions execute the finally logic, up until the handler which executes the except logic.
However, with the stack page guard exception, the process is different. None of the language's exception handlers will elect to handle this exception, because otherwise the stack growth mechanism would break. Instead, the filter search filters all the way through to the base exception handler provided by the OS, which grows the stack allocation by committing the appropriate memory, and then returns the appropriate return code to indicate that the OS should continue where it left off, rather than unwind the stack.
The tool and debugging infrastructure are designed to let these particular exceptions play out correctly, so you don't need to worry about handling them.
You can read more about SEH in Matt Pietrek's excellent article in MSJ from over a decade ago.
From looking at the comments, it looks to me like the "guard page exception" mess takes place entirely within the kernel, and is not something that you need to be worrying about from user space.
You've gotta remember that this article was written for C++, which is nowhere near as advanced as Delphi on the memory management front. The uninitialized pointers issue is a lot less of a mess in Delphi than in C/C++ for two reasons:
Delphi checks for uninitialized variables at compile time, which (for whatever reason) a lot of C compilers tend to have trouble with.
Delphi initializes all of its dynamic memory to 0, so you don't have random heap garbage to deal with that might look like a good pointer when it's really not. This means that most bad pointers give you access violations, which are easy to debug, instead of silently failing and corrupting memory.

Resources