From ca4179aa852127bb2e3bae6a9578e58440f68f9c Mon Sep 17 00:00:00 2001 From: Marcus Parsons Date: Sat, 20 Jul 2019 00:48:04 -0400 Subject: [PATCH] Added new section (#28311) Added new section about getting the message inside an exception --- guide/english/csharp/exceptions/index.md | 30 ++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/guide/english/csharp/exceptions/index.md b/guide/english/csharp/exceptions/index.md index ee4fae46e99..47060e7ad9b 100644 --- a/guide/english/csharp/exceptions/index.md +++ b/guide/english/csharp/exceptions/index.md @@ -8,7 +8,7 @@ An exception is an unexpected error that occurs while a program is running, such ## Example If we try to read the text of a file that does not exist: -``` +```csharp using System.IO; string content = File.ReadAllText(@"C:\DoesNotExist.txt"); @@ -22,11 +22,31 @@ Some other common exceptions: * `NullReferenceException`: Attempted to use an unassigned reference variable. * `DivideByZeroException`: Attempted to divide by 0. +## Get The Message Inside An Exception +Whenever you use the generic `Exception` catch all handler, you can grab the message of what caused the error each time. It is very simple to do so: + +```csharp + try + { + string content = File.ReadAllText(@"C:\DoesNotExist.txt"); + } + catch (Exception ex) + { + string message = ""; + if (ex.InnerException != null) { + message = ex.InnerException.Message; + } + else { + message = ex.Message; + } + Console.WriteLine(message); + } +``` ## Best Practices ### Use try/catch/finally Blocks -``` +```csharp try { var client = new WebClient(); @@ -46,7 +66,7 @@ finally Instead of -``` +```csharp try { conn.Close(); @@ -59,9 +79,11 @@ catch (Exception ex) Try this -``` +```csharp if (conn.State != ConnectionState.Closed) { conn.Close(); } ``` + +