locked
WinRT components and Exceptions

    Question

  •  

    I have a WinRT component in C++ that throws InvalidArgumentException as below:

    int Class1::MyMethod( int number ) { if( number == 2 ) { throw ref new InvalidArgumentException(); } return number * 5; }

    I am calling teh function as below:

    	Class1^ obj = ref new Class1();
    	try
    	{
    		int result = obj->MyMethod( 3 );
    		if( result == 15 )
    		{
    			int k =0;
    		}
    	}
    	catch( InvalidArgumentException^ e )
    	{
    		String^ err = e->Message;
    	}

    I have two questions regarding this...

    1) When it comes to throwing exceptions from winRT components, is it necessary that a function in a component should throw all possible exceptions?Instead of throwing the exception to the caller, can't I log the exception to some files?

    2) By the link http://msdn.microsoft.com/en-in/library/windows/apps/hh699896.aspx , you have to throw a WinRT exception only when it will cross application boundary interface(ABI), for example , when the code that catches your exception is written in Java Script. Does this mean that if i am calling a WINRT component from a C++ application I dont have to throw the exception? In this case, the above code will not be valid. If the component does not throw the exception, how would the client know about a failure? Can somepne please clarify?

    Monday, January 07, 2013 11:32 AM

Answers

  • I realize you are trying to show a point here with your example, but it's not a great example of the proper use of exception handling for C++.

    You should start by getting a good background on the best way to utilize C++ exception handling in general. If you were to read only a single book, I'd suggest:

    Scott Meyers. More Effective C++. Addison-Wesley, 1996. Print.

    Internally your C++ program is free to use whatever mechanism you want for error handling, but when you return errors from WinRT methods they could be called from C++, C#, or JavaScript. Therefore exception handling is the only way to communicate errors to these kinds of programs.

    That said, this is more a design issue. You really shouldn't have WinRT methods that can't handle something like a '2' as a parameter. Exceptions should be used in exceptional cases like a pointer that should never be null being null, a file that should always be present is missing, a memory allocation (which with virtual memory should never fail) fails, etc.

    You should have a more systematic approach to dealing with what are programming errors in your app: assert, defensive programming, etc. User input from UI or data files should be validated before being passed to such functions.

    You should also learn how to write 'exception-safe' C++ code which is primarily embracing RAII style handling of resources. I have some examples of this in my Dual Use Coding Techniques for Games blog post.

    Monday, January 07, 2013 7:59 PM