User FAQs

If you have a question, please send it to us.


1) Can you describe the purpose of a Try-Catch-Finally block ?
The try block encloses those statements that might cause an exception.
The catch block can handle exceptions.
The finally block always executes and contains any cleanup code.

try 
{ }
catch
{ }
finally
{ }

2) Should your local variables be declared before the try block or inside the try block ?
All local variables should be declared inside the try block.
This prevents them from being 'accidentally' used in the catch or finally blocks.

try 
{
   string myString = System.String.Empty;
   long myNumber = 100;

3) Can you have a Try block with no Catch block or Finally block ?
No. A Try block must be followed by either a Catch block, a Finally block or both.


4) Can multiple Catch blocks be executed ?
No. When an exception occurs the correct catch block is executed and then control is passed to the Finally block (if one exists).


5) What happens if the exception is not matched by a Catch block ?
The exception will be treated as unhandled and will propogate up the call stack.


6) When does the Finally block get executed ?
It always gets executed even if an exception occurs.

finally 
{ }

7) Can you put a return statement inside a Finally block ?
No. The Finally block is always completed in full and cannot be exited before the end. You will get a compile error.


8) What would the syntax be to catch any possible type of Exception ?

catch 
catch (System.Exception)
catch (System.Exception ex)

9) Can you define your own User Defined Exceptions ?
Yes. You can derive from the System.Exception class.
Never use the System.ApplicationException class.

class UserNameInvalidException : System.Exception 
{
   class UserNameInvalidException(string MyMessage) : base (MyMessage)
   {}
}

10) Is there any difference between the following lines of code ?
Yes. The three different throws will all do something slightly different.

try 
{ }
catch (System.Exception ex)
{
   throw;
   throw ex;
   throw new System.Exception("message", ex);
}

throw - will rethrow the original exception and preserve the stack trace.
throw ex - will rethrow the original exception but resets the stack trace.
throw new System.Exception - will create a brand new exception which resets the stack trace and loses the type of exception.


11) Can you give some examples of different types of Exceptions ?
ArgumentNullException - An argument that is passed to a method has a null value.
IndexOutOfRangeException - An index is outside the bounds of an array or collection.
StackOverflowException - An arithmetic, casting or conversion operation results in an overflow.
DivideByZeroException - The denominator in an Integer or Decimal division is zero.



© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext