CHAPTER 21

image

Exception Handling

Exception handling allows programmers to deal with unexpected situations that may occur in programs. As an example, consider opening a file using the StreamReader class in the System.IO namespace. To see what kinds of exceptions this class may throw, you can hover the cursor over the class name in Visual Studio. For instance, the System.IO exceptions FileNotFoundException and DirectoryNotFoundException. If anyone of those exceptions occurs, the program will terminate with an error message.

using System;using System.IO; class ErrorHandling{   static void Main()  {     // Run-time error    StreamReader sr = new StreamReader("missing.txt"); ...

Get C# Quick Syntax Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.