Error Handling in C# with Exceptions Flashcards
Why handling errors? list 4 reasons
- So the program doesnt crash.
- Gives the chance to fix/retry.
- meaningful message and graceful exit
- opportunity to log erros
Why using exceptions instead of error codes?
more readable , exceptions can bubble up, can catch excptions at higher levels or sigle place… handle system errors… better documentable in the constructors.
What an exception is made of?
Is an object that inherits from system.Exception and is created via throw statement.
What is an exception?
any error condition or unexpected behavior that is encountered by an executing program.
how exceptions are organized?
via an hierarchy of classes.
see here: https://pasteboard.co/JCvqsHk.png
What are the properties exposed by an exception class?
Message: the explataion of what happened.
Stack trace: all the call chain.
Data: key value pair with extra data.
InnerException: Exception that caused the exception.
Source: application/object name that caused the error (assembly).
Help link: help information about the error;
Target site: method that threw the exception plus a lot of good information reflected.
What are the guidelines of an ApplicationException and SystemException class?
should not be thrown, extended or caught (unless you plan rethrowing it)
What should i do when I want to catch an OutOfMemoryException?
call Environment.FailFast to terminate the app and log to the console
What happens when an exception is not handled by the application or framework?
the app will crash (stopped working).
How to create try catch block that treats different exception types? Does the order matter?
multiple catches are defined… the order is from most specific to least specific. top down
What are some exception handling good practices?
- catch blocks that swallow exceptions;
- invalid inputs, for eg, is not and exceptional situation.. you need to validate (or code to handle that).
- Design code to avoid exceptions.
- Localize error messages (the exceptions itself).
- use finally for cleanups.