Could you explain the concept of exceptions in C#?
Check out the MSDN Docs on Exceptions.
Put simply, an Exception occurs whenever there is some error in the application. There are many different types of errors, such as array indexes going out of bounds, errors in disk I/O, Divide By Zero problems, etc. But in general, Exceptions occur whenever something happens that the program could not automatically correct for.
Exception is a situation when a method or function cannot do what it is supposed to do.
If OpenFile method cannot open the file [for whatsoever reason] and return the file handle to caller, this is an exception for the OpenFile method because it could not open the file which is its primary purpose. As such there's nothing like exception, what may be an exception to you might be chronic to someone else in some different context. We can call it Execution Failures
. Primary purpose of the exceptions is to communicate the error conditions.
Ex: OutOfMemoryException
might be an exception condition for normal small scale data-entry applications but not for those applications that do their memory management on their own, like SqlServer or IIS. Consider a case of reading a stream. If the ReadByte
method reaches to end of stream and there's no more byte to read, at that time when you call ReadByte on the stream it should thrown an exception because there are no more bytes to read. But when you call ReadChar
method at the end of stream, It will read EOF which is absolutely ok for ReadChar method since EOF is a valid character to read. For ReadByte method condition is called as method-failure