C# ClassesLesson 36Free preview
C# Exceptions
This lesson is part of C# · All levels
Summary
An exception is a state of error that occurs when a program is running, such as dividing by zero or reading an empty file. C# handles it with try, catch, and finally block so that the program can continue to execute safely. You can also throw your own exception with a throw to report an invalid condition.
Key points
- The try block contains risky code, catch catches exception, and finally always runs.
- The common exceptions are DivideByZeroException, FormatException, IndexOutOfRangeException, and FileNotFoundException.
- The throw new exception statement is used to throw the exception itself with a statement message.
- It's best to capture specific types of exceptions, not all exceptions in one empty catch.
- The block finally suits to clean up the resource like closing a file or connection.
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.