Welcome to real time world. here you would be learning all the Real time C# questions asking in interviews.
1. Which catch block will be executed in the following code snippet.
Output : In the above code snippet the output will be a compile time error.
Why: Exception is parent type of all exceptions so it should be placed at last in the catch block order, that is why we will get compile time error saying A previous catch clause already catches all exceptions of this or of a super type (‘Exception’) as shown in the below picture.
that means if you want to use parent Exception at fist place, you don’t need to mention other child exception types.
Solution: If you want to use all parent and child exceptions, you can do that by placing parent exception type at last as shown in the below code snippet 2.
2. What is the output of the following code snippet 1
Case 1. when exceptioned
Case 2. when no exception
Output: Compile time error in both the cases.
Why?: we can’t write return statement in finally block.
You can see the actual error thrown by compiler in the below screenshot
Solution: just remove the return statement from finally statement.
3. What is the output of the following code snippet 1
1. Normally we think that output is
but this output is wrong.
2. The correct output is
when we look at return statement in catch block, we think that the cursor will return from there, but finally block will be executed always. That is why the output is try, catch, finally
4. What are exception filters?
5. What is the difference between an error and exception?
An exception is a class that takes advantage of language semantics. As others have stated, exceptions interrupt execution up the stack until caught. An exception can be used to convey an error, but more generally is used to convey that something exceptional has occurred.
Errors, on the other hand, can be exceptional or not.
There are several kinds of errors:
- User error – this should be handled without an exception
- Syntax error – this shouldn’t compile in statically typed languages (in dynamic languages, they’re a little harder to discover)
- Runtime error – this will either result in an exception, or silently fail (usually creating unexpected results)
Really, exceptions should be limited to handling runtime errors, since a user inputting bad data is not “exceptional.” To handle user errors, you should take the following approaches:
- Prevent bad data from being input (front-end validation)
- Prevent bad data from being persisted (back-end validation)
Exceptions should be used as a “last line of defense” for user error. If you’re writing a persistence layer, you can rely on exceptions to ensure that bad data that falls through validation does not get persisted. You should, however, fix any of these by putting a fix in the validation that prevents the error from occurring in the first place.
preparing more questions