Book Image

C# 7 and .NET: Designing Modern Cross-platform Applications

By : Mark J. Price, Ovais Mehboob Ahmed Khan
Book Image

C# 7 and .NET: Designing Modern Cross-platform Applications

By: Mark J. Price, Ovais Mehboob Ahmed Khan

Overview of this book

C# is a widely used programming language, thanks to its easy learning curve, versatility, and support for modern paradigms. The language is used to create desktop apps, background services, web apps, and mobile apps. .NET Core is open source and compatible with Mac OS and Linux. There is no limit to what you can achieve with C# and .NET Core. This Learning Path begins with the basics of C# and object-oriented programming (OOP) and explores features of C#, such as tuples, pattern matching, and out variables. You will understand.NET Standard 2.0 class libraries and ASP.NET Core 2.0, and create professional websites, services, and applications. You will become familiar with mobile app development using Xamarin.Forms and learn to develop high-performing applications by writing optimized code with various profiling techniques. By the end of C# 7 and .NET: Designing Modern Cross-platform Applications, you will have all the knowledge required to build modern, cross-platform apps using C# and .NET. This Learning Path includes content from the following Packt products: • C# 7.1 and .NET Core 2.0 - Modern Cross-Platform Development - Third Edition by Mark J. Price • C# 7 and .NET Core 2.0 High Performance by Ovais Mehboob Ahmed Khan
Table of Contents (25 chapters)
Title Page
Copyright
About Packt
Contributors
Preface
16
Designing Guidelines for .NET Core Application Performance
Index

Handling exceptions when converting types


You've seen several scenarios when errors have occurred when converting types. C# calls this, an exception has been thrown.

Good practice is to avoid writing code that will throw an exception whenever possible, perhaps by performing if statement checks, but sometimes you can't. In those scenarios, you must catch the exception and handle it.

As you have seen, the default behavior of a console application is to display details about the exception in the output and then stop running the application.

You can take control over how to handle exceptions using the try statement.

The try statement

Add a new console application project named HandlingExceptions.

When you know that a statement can cause an error, you should wrap that statement in a try block. For example, parsing from a string to a number can cause an error. We do not have to do anything inside the catch block. When the following code executes, the error will get caught and will not be displayed, and the console application will continue running.

In the Main method, add the following statements:

WriteLine("Before parsing");
Write("What is your age? ");
string input = Console.ReadLine();
try
{
   int age = int.Parse(input);
   WriteLine($"You are {age} years old.");
}
catch
{
 
}
WriteLine("After parsing");

Run the console application and enter a valid age, for example, 43:

Before parsing
What is your age? 43
You are 43 years old.
After parsing

Run the console application again and enter an invalid age, for example, kermit;

Before parsing
What is your age? kermit
After parsing

The exception was caught, but it might be useful to see the type of error that occurred.

Catching all exceptions

Modify the catch statement to look like this:

catch(Exception ex)
{  
   WriteLine($"{ex.GetType()} says {ex.Message}");
} 

Run the console application and again enter an invalid age, for example, kermit:

Before parsing
What is your age? kermit
System.FormatException says Input string was not in a correct format.
After parsing

Catching specific exceptions

Now that we know which specific type of exception occurred, we can improve our code by catching just that type of exception and customizing the message that we display to the user.

Leave the existing catch block, but add the following code above it:

catch (FormatException)
{
   WriteLine("The age you entered is not a valid number format.");
} 
catch (Exception ex) 
{ 
   WriteLine($"{ex.GetType()} says {ex.Message}"); 
} 

Run the program and again enter an invalid age, for example, kermit:

Before parsing
What is your age? kermit
The age you entered is not a valid number format.
After parsing

The reason we want to leave the more general catch below is that there might be other types of exceptions that can occur. For example, run the program and enter a number that is too big for an integer, for example, 9876543210:

Before parsing
What is your age? 9876543210
System.OverflowException says Value was either too large or too small  for an 
Int32.
After parsing

Let's add another catch for this new type of exception:

catch(OverflowException)
{
   WriteLine("Your age is a valid number format but it is either too big or small.");
}
catch (FormatException)
{
   WriteLine("The age you entered is not a valid number format.");
}

Rerun the program one more time and enter a number that is too big:

Before parsing
What is your age? 9876543210
Your age is a valid number format but it is either too big or small.
After parsing

Note

The order in which you catch exceptions is important. The correct order is related to the inheritance hierarchy of the exception types. You will learn about inheritance in Chapter 3, Building Your Own Types with Object-Oriented Programming. However, don't worry too much about this—the compiler will give you build errors if you get exceptions in the wrong order anyway.