Using 'throw' statement to raise an exception
Remember the old days where you will get an error code back when you call a COM object and then search all over the Google to find what this stupid number mean ?
Those days are gone. No more error codes and magic numbers. In .net, if there is an error, you will get an exception.
NOTE: Exception/Error is different from 'false'. If you have a method called 'IsNumber()', it should return false if the passed parameter is not a number, and not an Exception. Exceptions should be raised only if there is an unexpected error.
How to Raise an Exception ?
You can raise an exception using the 'throw' statement. In your code, you can check for error conditions and create and throw appropriate exceptions. The caller of the method need not check for error codes returned from a method. See the following sample code :
private void SaveData( Object data ) { if ( data == null ) { // Create and throw an exception of type 'ArgumentNullException'. throw new ArgumentNullException(); } }
You can also re-throw a caught exception using the 'throw' statement.
try { // Some code that may cause an exception. // ... } catch ( Exception ex ) { // Re-throw the same exception so that the caller of this method // can catch this exception. throw; }
The above code will simply re-throw the exception which was caught. This would be useful if you want to perform some error logging and then re-throw the exceptions.
But it is always a good practise to add more information to the exception before you re-throw it. For this, you can create a new exception and embed the caught exception as 'inner-exception' in the new exception you create.
try { // Some code that may cause an exception. // ... } catch ( System.IO.FileNotFoundException ex ) { // Create a new exception with additional information and embed // the original exception as inner-exception. throw new System.IO.FileNotFoundException( "An error occurred in the method 'SaveData()'. The file 'C:\app.txt' doesn't exists.", ex ); }
The 'throw' statement can be used to throw custom exceptions also. It is a good practise to create custom exceptions for your application and throw custom exception in case of application errors. For example, you can have custom exception classes like 'DataFileNotFoundException', 'UserNotSignedInException' etc.
|
No responses found. Be the first to respond and make money from revenue sharing program.
|