Is it possible to catch an "object not initialized" exception in Dynamics AX? - dynamics-ax-2009

Problem:
I have some code that is failing because an object has not been initialized. The solution for this bug is easy to fix, when detected. However, what surprised me is that my elaborate exception handling didn't catch this exception. That meant the exception wasn't logged or handled, and code following the try catch block was never executed. The try...catch block was outside of the transaction, so there was no issue there.
In this particular case, the exception was inside a batch (RunBaseBatch) job. The job handled several unrelated processing tasks. Once the exception conditions were met, the job terminated, so the other unrelated processing tasks were never called.
Does anyone know if it is possible to catch an "object not initialized" exception in Dynamics AX 2009? I read one post that said it may not be possible to catch certain exceptions in AX, however, I hope that is not the case (reference: https://community.dynamics.com/product/ax/f/33/p/16352/23700.aspx#23700).
Code example:
Here is some simplistic code that recreates the issue:
server static void main(Args args)
{
Array arr;
;
info ("debug: before try...catch");
try
{
// ttsbegin; // enable/disable to test with transactions
// arr = new Array(Types::String); // Enabling this line will prevent the exception
arr.exists(3);
// ttscommit; // enable/disable to test with transactions
}
catch (Exception::Internal) // This exception handler was the Magic Sauce!!
{
info ("debug: catch (Exception::Internal)");
}
catch (Exception::Error)
{
info ("debug: catch (Exception::Error)");
}
catch
{
info ("debug: catch");
}
info ("debug: after try...catch");
}
UPDATE 2013-01-29
I am waiting to accept an answer until this question has been viewed more. Thank you for the answers so far.
I know the example I gave was simplistic. This type of bug is easily fixable when it is known. And defensive programming is always a good idea.
However, in the real world, the code where the bug occurred was very complex. The error occurred several levels deep in an overloaded method of a subclass. It occurred in a specific scenario, when an overloaded method corrupted the protected value of a member variable from the super class. That is where the bug occurred in the code, however, it didn't manifest itself until the super class tried to use the member variable again. The bug was summarily fixed when it was detected and tracked down.
Defensively, yes you could check every protected member variable, every time you use it, but that does start to impact performance, code readability, practicality, etc., which is why languages offer exception handling.
The question here, is how can these type of bugs be caught to make code more robust and bullet-proof? In most development environments (C, C++, C#, or Java for example), a try...catch at a top level could be used to catch, log, and clean up ALL unexpected exceptions. So the code would be able to continue processing with the other unrelated tasks. AX is continuing at some level, because the whole system doesn't come to a grinding halt when this bug occurs. However, the code after the catch in this job is not executing because of what appears to be a deficiency in AX/X++.
I am looking for an innovative solution or work-around, if it exists, to catch the "object not initialized" exception (really ALL exceptions) and to continue processing.

You cannot "catch" it in the traditional sense, but you can avoid it happening. Simply test if the object exists before running anything from it:
if(object)
{
// Exists; Execute statements with object here
}
else
{
// Doesn't exist
}
This works because object will be translated as null if it is not initialized.
(Null == 0) == false
If the object is initialized it will have some value other than null.
(!Null != 0) == true
Hope that helps!

You can, but you shouldn't. A behavior like this is almost certainly a bad design of your code, that will inevitably end in more problems in the future.
You need to make your code defensive to this case, making sure the object is instanciated before using it. Otherwise, you're using the catch code to an expected behavior, wich makes no sense.
EDIT 2013/02/18
In complex scenarios like what you're describing, it's usually very hard to get a solution fully controlled. In AX, try..catch statement is quite simplified and in a very large range of situations is not really needed (unlike Java, C#, ... where is always recommended).
This simplification is nice in almost all situations of AX development, as you don't need to waste time on exception handling. Just let them raise, and the InfoLog will handle them on a simple and reliable way.
The big problem comes where you really need this control... when there is not really a way of force it. I'm not sure if this is really an standard issue or it's espected by the product team to work that way, but this cases are always giving troubles in AX. When you need to catch some specific issue you have to be very creative and deffensive to prevent the exception as catching it will become even more creative...
Hope this helps :)

To elaborate a little, as stated in the post you linked to you cannot catch an Object Not Initialized error. However, you can "fix" the code by adding a simple check before attempting to run functions against a variable that you do not control (for example, if you are requesting an Array type as an argument for a function and you expect the function to be called from outside the class).
try
{
if (arr)
arr.exists(3);
}
The if(arr) statement is enough to skip the processing if the object has not yet been instantiated, effectively bypassing the error. However, this will obviously not throw the error further up the chain. If you really wanted, you could make it throw a different error that can be caught, but obviously that is less than ideal.
In this case, since the RunBaseBatch class may not be something you want to modify it would probably be better to make sure the object that is causing the issue is correctly defined before calling the problem method, and finding these errors in testing.

Related

How to give warning message in Visual Studio when passed an unappropriate parameter to a method?

I know that it is nonsense (or there is no chance) for variables that its value is unknowable until the runtime.
Let's assume that you have a method like this:
public void Foo (BarEnum barVal)
{
//...
if(barVal == BarEnum.UnappropriateForFooMethod)
throw new BlaBlaException("Invalid barVal for Foo method ->" + barVal);
//...
}
This method will already throw an exception for unappropriate parameter. But I intend to warn developer that before run code and get an exception. Main idea is that. It is not important that if she/he do not care about warnings or turned off the warning messages, her/him code will get an exception anyway.
I guess that it is possible with built-in attributes. Like Obsolete. But I could not find anything...
If there is no attribute for this purpose, I am open to suggestions for custom solutions.
From .NET Framework 4 and later there's something called Code Contracts (on GitHub). Never tried it, but looks like what you seek.
There's also Roslyn. Also haven't work with it, but probably does at least something that you want. Being a super-tool, it is probably a bit unwieldy and verbose for your needs.
One workaround to this problem, without using external tools, is to thoroughly review the code.

How to deal with bad_alloc in RAII?

The code is as follows:
class A;
shared_ptr<A> aPtr(new A());
//do something with aPtr.
If new throws a bad_alloc exception, what happend to the smart point aPtr? Do I need to do some check with aPtr, and how to do? And I know one of the Google C++ program rules is never using exceptions, but how they deal with exceptions like bad_alloc? Thank you for any replies.
If you get a bad_alloc you're pretty much screwed anyway. I'm not sure how you expect to handle the allocation failing here. Not using exceptions does not really apply in this case.
If you really want to opt out of it you can add a nothrow to that statement and it'll return nullptr instead of throwing a bad_alloc:
shared_ptr<A> aPtr(new (std::nothrow) A());
For more information see this question about the design consideration involved. Additionally see this question explainign why using std::nothrow is a bad idea.

Confused with Uncle Bob explanation on handling Null objects in book Clean Code

I was reading Uncle Bob book today on Exception handling and what I could recollect from handing null values was that methods should not be handling null values because it clutters the code. I am a little confused with it.
I have always thought that a method should always make sure that it's dependencies are not null (unless they are injected in constructor and constructor assures of nullability).
For example, if I have a method
public void SendMessage(IEmailSender emailSender, contactList list)
{
if(emailSender == null)
{
throw new ArgumentNullException("Failed to send
message.",MethodBase.GetCurrentMethod().GetParameters[0].Name);
}
if(list == null)
{
throw new ArgumentNullException("Failed to send
message.",MethodBase.GetCurrentMethod().GetParameters[1].Name);
}
// rest of code goes here
}
Am I missing something?
There are two perspectives:
On the one hand, with your approach you would always tell the caller what exactly he did wrong by calling your method. Which is great for the caller because he can fix it right away when he gets your exception. This would be true and valid if you where writing API code that is used by a third party.
On the other hand, if you call your method yourself, a reasonable argument to throw an exception is, because you want to be able to handle this situation with a catch block inside your calling code! If you have no reason to handle it somewhere, why throwing an exception at all? The only reason i see is, to have a detailed error logging by catching those exceptions in a GlobalExceptionHandler.
So you see we have two categories of exceptions here: The one for developers, to avoid wrong usage of APIs, and the other one to be used as the method's error-result.
If you are writing API code that will be used by others, your choice would be, not to listen to Bob ;-)
For those who did not read CleanCode, Bob is suggesting two things:
1.You should not write methods that return null (To avoid unnecessary checks afterwards). So Instead of writing this:
var myObject = GetObjectThatDoesSomthing();
if(myObject != null)
{
myObject.DoSomething();
}
... you should be able to write this:
var myObject = GetObjectThatDoesSomething();
myObject.DoSomething();
Cleaner.
2.You should not pass null to your methods to avoid unnecessary checks at the beginning of a method, like here:
public Point Add(Point p1, Point p2)
{
if(p1 == null) throw ArgumentException();
if(p2 == null) throw ArgumentException();
...
}
The point of these rules is: if you stick with it, you know that you dont have to write these null-checks and your code gets cleaner and easier to read. But at the moment you are using third party code, you are not able to tell if they have applied the same rules in their API, so you are starting to pre- or postcheck again. The same thing when you write an API for others: How do the consumers of your API know that you have coded with Bobs rules in mind...
I haven't read the book but I can only imagine that Uncle Bob is advocating the use of the Null Object Pattern in preference to explicit null reference handling.
for example, rather than
if(log != null)
log.Write("My log message");
You could instead create an ILogger interface containing a Write method and create two classes that implement this interface: a NullLogger and a FileLogger. The NullLogger would have an empty body for the Write method's implementation.
In my mind this is different to your explicit pre-condition validation that you have in your example
It depends what type of code are you writing.
If your public method is designed to be used by the wide range of developers non familiar with usage it makes always sense to check parameters and throw a verbose exception.
If you are writing a private method which is only used from the same class or some internal called by another friendly class also written by you or by your collaborator it makes less sense to make paranoia null checks. Your injection design and tests must ensure your internas are not getting null values.
And if private/internal method parameters still get nulls it is anyway too late. Throwing ArgumentNull exception form a private/internal method does not help external user to fix the cause, so it makes no difference for him either to get ArgumentNull or NullReference exception.

Benefits of Assertive Programming

What is the point of putting asserts into our code ? What are the benefits of assertive programming ?
private void WriteMessage(string message)
{
Debug.Assert(message != null, "message is null");
File.WriteAllText(FILE_PATH, message);
}
For example we can check the message variable and throw an exception here. Why do I use assert here ? Or is this a wrong example to see benefits of asserts ?
They also support the philosophy of fail fast, explained in this article by Jim Shore.
Where some people would write:
/*
* This can never happen
*/
Its much more practical to write:
assert(i != -1);
I like using asserts because they are easily turned off with a simple compile time constant, or made to do something else like prepare an error report. I don't usually leave assertions turned on (at least, not in the usual way) when releasing something.
Using them has saved me from making very stupid mistakes on other people's computers .. those brave souls who enjoy testing my alpha code. Using them plus tools like valgrind helps to guarantee that I catch something awful before committing it.
An important distinction to consider is what sorts of errors you would like to catch with assertions. I often use assertions to catch programming errors (i.e., calling a method with a null parameter) and a different mechanism to handle validation errors (e.g., passing in a social security number of the wrong length). For the programming error caught with the assertion, I want to fail fast. For the validation error, I want to respond less drastically because it may be normal for there to be errors in the data (e.g. a user doing data entry of some sort). In those cases the proper handling might be to report the error back to the user and continue functioning.
If there is a specified pre-condition for the method to take a non-null message parameter, then you want the program to FAIL as soon as the pre-condition doesn't hold and the source of the bug must then be fixed.
I believe assertions are more important when developing safety-critical software. And certainly you would rather use assertions when the software has been formally specified.
For an excellent discussion of assertions (and many other topics related to code construction), check out Code Complete by Steve McConnel. He devotes an entire chapter to effective use of assertions.
I use them to verify that I have been supplied valid dependent class. for exmaple in constructor DI, you usually are accepting some sort of external class that you are dependent on to provide some action or service.
so you can assert(classRef !- null,"classRef cannot be null"); instead of waiting for you to pass a message to classRef and getting some other exception such as exception : access violation or something equally ambiguous that might not be immediately obvioius from looking at the code.
It is very useful to test our assumptions. The asserts constantly make sure that the invariant holds true. In short it is used for the following purposes,
It allows to implement fail-fast system.
It reduces the error propagation because of side-effects.
It forbids(kind of sanity-check) the system to enter an inconsistent state because of user-data or by subsequent code changes.
Sometimes, I favor the use of assert_return() when we do not want to use try/catch/throw.
private void WriteMessage(string message)
{
assert_return(message != null, "message is null"); // return when false
File.WriteAllText(FILE_PATH, message);
}
I suggest assert_return() to halt the application by reporting an error in test build. And then in the production system, it should log and error and return from the function saying it cannot do that.

How can I test for an expected exception with a specific exception message from a resource file in Visual Studio Test?

Visual Studio Test can check for expected exceptions using the ExpectedException attribute. You can pass in an exception like this:
[TestMethod]
[ExpectedException(typeof(CriticalException))]
public void GetOrganisation_MultipleOrganisations_ThrowsException()
You can also check for the message contained within the ExpectedException like this:
[TestMethod]
[ExpectedException(typeof(CriticalException), "An error occured")]
public void GetOrganisation_MultipleOrganisations_ThrowsException()
But when testing I18N applications I would use a resource file to get that error message (any may even decide to test the different localizations of the error message if I want to, but Visual Studio will not let me do this:
[TestMethod]
[ExpectedException(typeof(CriticalException), MyRes.MultipleOrganisationsNotAllowed)]
public void GetOrganisation_MultipleOrganisations_ThrowsException()
The compiler will give the following error:
An attribute argument must be a
constant expression, typeof expression
or array creation expression of an
attribute
Does anybody know how to test for an exception that has a message from a resource file?
One option I have considered is using custom exception classes, but based on often heard advice such as:
"Do create and throw custom exceptions
if you have an error condition that
can be programmatically handled in a
different way than any other existing
exception. Otherwise, throw one of the
existing exceptions." Source
I'm not expecting to handle the exceptions differently in normal flow (it's a critical exception, so I'm going into panic mode anyway) and I don't think creating an exception for each test case is the right thing to do. Any opinions?
I would recommend using a helper method instead of an attribute. Something like this:
public static class ExceptionAssert
{
public static T Throws<T>(Action action) where T : Exception
{
try
{
action();
}
catch (T ex)
{
return ex;
}
Assert.Fail("Exception of type {0} should be thrown.", typeof(T));
// The compiler doesn't know that Assert.Fail
// will always throw an exception
return null;
}
}
Then you can write your test something like this:
[TestMethod]
public void GetOrganisation_MultipleOrganisations_ThrowsException()
{
OrganizationList organizations = new Organizations();
organizations.Add(new Organization());
organizations.Add(new Organization());
var ex = ExceptionAssert.Throws<CriticalException>(
() => organizations.GetOrganization());
Assert.AreEqual(MyRes.MultipleOrganisationsNotAllowed, ex.Message);
}
This also has the benefit that it verifies that the exception is thrown on the line you were expecting it to be thrown instead of anywhere in your test method.
The ExpectedException Message argument does not match against the message of the exception. Rather this is the message that is printed in the test results if the expected exception did not in fact occur.
Just an opinion, but I would say the error text:
is part of the test, in which case getting it from the resource would be 'wrong' (otherwise you could end up with a consistantly mangled resource), so just update the test when you change the resource (or the test fails)
is not part of the test, and you should only care that it throws the exception.
Note that the first option should let you test multiple languages, given the ability to run with a locale.
As for multiple exceptions, I'm from C++ land, where creating loads and loads of exceptions (to the point of one per 'throw' statement!) in big heirachies is acceptable (if not common), but .Net's metadata system probably doesn't like that, hence that advice.
I think you can just do an explicit try-catch in your test code instead of relying on the ExpectedException attribute to do it for you. Then you can come up with some helper method that will read the resource file and compare the error message to the one that comes with the exception that was caught. (of course if there wasn't an exception then the test case should be considered a fail)
If you switch over to using the very nice xUnit.Net testing library, you can replace [ExpectedException] with something like this:
[Fact]
public void TestException()
{
Exception ex = Record.Exception(() => myClass.DoSomethingExceptional());
// Assert whatever you like about the exception here.
}
I wonder if NUnit is moving down the path away from simplicity... but here you go.
New enhancements (2.4.3 and up?) to the ExpectedException attribute allow you more control on the checks to be performed on the expected Exception via a Handler method. More Details on the official NUnit doc page.. towards the end of the page.
[ExpectedException( Handler="HandlerMethod" )]
public void TestMethod()
{
...
}
public void HandlerMethod( System.Exception ex )
{
...
}
Note: Something doesn't feel right here.. Why are your exceptions messages internationalized.. Are you using exceptions for things that need to be handled or notified to the user. Unless you have a bunch of culturally diverse developers fixing bugs.. you shouldn't be needing this. Exceptions in English or a common accepted language would suffice. But in case you have to have this.. its possible :)
I came across this question while trying to resolve a similar issue on my own. (I'll detail the solution that I settled on below.)
I have to agree with Gishu's comments about internationalizing the exception messages being a code smell.
I had done this initially in my own project so that I could have consistency between the error messages throw by my application and in my unit tests. ie, to only have to define my exception messages in one place and at the time, the Resource file seemed like a sensible place to do this since I was already using it for various labels and strings (and since it made sense to add a reference to it in my test code to verify that those same labels showed in the appropriate places).
At one point I had considered (and tested) using try/catch blocks to avoid the requirement of a constant by the ExpectedException attribute, but this seemed like it would lead to quite a lot of extra code if applied on a large scale.
In the end, the solution that I settled on was to create a static class in my Resource library and store my exception messages in that. This way there's no need to internationalize them (which I'll agree doesn't make sense) and they're made accessible anytime that a resource string would be accessible since they're in the same namespace. (This fits with my desire not to make verifying the exception text a complex process.)
My test code then simply boils down to (pardon the mangling...):
[Test,
ExpectedException(typeof(System.ArgumentException),
ExpectedException=ProductExceptionMessages.DuplicateProductName)]
public void TestCreateDuplicateProduct()
{
_repository.CreateProduct("TestCreateDuplicateProduct");
_repository.CreateProduct("TestCreateDuplicateProduct");
}

Resources