Saturday 10 December 2016

Exception Handling

Exception Handling (try- catch- finally)


What happens if a finally block throws an exception?


Three things will be happen

ONE # That exception propagates out and up, and it should be handled at a higher  level. If it is not handled at the higher level, the application crashes.

TWO # The "finally" block execution stops at the point where the exception thrown.

Three # 
a) if the "finally" block is being executed after an exception has occurred in the try block,
b)and if that exception is not handled 
c) and if the finally block throws an exception
Then the original exception occurs in the try block is lost.



Will finally run if i put return in catch block?

Yes.The finally section is guaranteed to execute whatever happens including exceptions or return statement.


Does finally get executed if the code throws an error ?

Finally is always executed.


Is it mandatory for a piece of code to have catch or finally when try block is there ?

Yes. If a try block is there then either catch or finally has to be there or else a compiler error is generated.


Can finally bock have return statement ?

No,a compile time error is generated. Thats bcz finally contains the clean up code.


Can there be many catch statements for a single try block ?

Yes.But the rule is most specific exceptions should be caught first.


Will the foll code compile ?

           try 
            {
                throw new SystemException();
            }            
            catch(Exception e)
            {
            }
            catch(ArgumentException e)
            {
            }
No.It gives the foll error
A previous catch clause already catches all exceptions of this or of a super type ('System.Exception')





Thank you for taking your valuable time look at my blog - Sadiq Ali Syed



No comments: