Computer Studies - Type Conversions and Exceptions Type Conversions and Exceptions The user interface controls ( Label1.Text / TextBox1.Text ) and methods ( Console.WriteLine() / Console.ReadLine() ) always expect to work with string data. Many of our programs work with numeric data therefore we must have effective ways of converting data between string and numeric data types. Strings to Numeric Conversions There are a set of conversion methods available depending on the target numeric data type. Pattern is : <data type>.Parse(<string data>) Example int age = int.Parse("32"); double shoeSize = double.Parse ("8.5"); decimal wage = decimal.Parse ("15.25"); Numeric to String Conversions To convert numeric literals or numeric variables to strings the method ToString()can be used. Examples int age = 15; string message = "You are " + age.ToString() + "years old." TextBox1.Text = message; Label1.Text = age.ToString(); // Text property is a string data type Note: When you perform string concatenation (+) C# will automatically call the ToString() method to convert numeric data to a string data type. The Console.WriteLine() method will also perform the same action. Remember that for Text Properties on labels and textboxes this automatic conversion does not occur. Computer Science Notes [1] Type Conversions and Exceptions Computer Studies - Type Conversions and Exceptions Error Handling with Exceptions What happens when the string that is to be converted / parsed into a numeric value is not a valid number? A runtime error will occur. Example If you are testing / running the program from Visual Studio the statement that caused the error / exception is highlighted and the name of the exception is provided. In this case the exception is called a FormatException. What are Exceptions? Exceptions are basically runtime errors that can occur and they are categorized by the type of problem encountered. When an exception occurs the programmer can detect it using a try {} / catch {} block of code. Each exception is part of a hierarchy with the most general exception being called Exception. As you can see in the example above this was a FormatException. Therefore, we could intercept or catch this exception using the generic Exception object or a more specific FormatException. How to capture runtime errors and handle them? To capture a runtime error you simply surround the code to be protected with a try block of code. If a runtime error occurs at any point within the protected code processing will stop and the exception handling block will be executed. The exception handling section is always immediately after the try block. Handling exceptions involves the use of one or more catch code blocks. You can think of catch blocks as a sequence of conditions that are checked when errors occur. The argument for the catch statement involves naming the type of exception to be matched. Let's look at a few examples. Examples Output Computer Science Notes [2] Type Conversions and Exceptions Computer Studies - Type Conversions and Exceptions In this example, any runtime error that might occur on the single statement within the try block would cause the catch block to be executed. There is a single generic Exception defined for this catch block and two (2) messages would be displayed. The first one is "Something went wrong" and it was created by the programmer. The second message was automatically created and it is stored in the Message field of the Exception object named ex. Example In this example we captured a more specific type of exception first and generated a specific message that explained the issue in greater detail. If a different type of exception occurred the first catch block would be skipped and the second one executed. You can define try / catch blocks anywhere in your code. Computer Science Notes [3] Type Conversions and Exceptions Computer Studies - Type Conversions and Exceptions Preventing Data Conversion Exceptions The <data type>.Parse() method is used often to convert string data coming from users into numeric data types to perform calculations. Instead of letting the exceptions occur and providing the user with an error message how about we avoid the exception all together using the <data type>.TryParse() method. General format of the TryParse method bool int.TryParse( string, out targetVariable ) The keyword out is mandatory. The target variable should be declared as an integer datatype. The method returns a boolean value of true if the parsing is successful otherwise it returns false. Examples Here is another example using TextBox validation. Computer Science Notes [4] Type Conversions and Exceptions Computer Studies - Type Conversions and Exceptions Exercises 1. What value does a TryParse method return if the string argument is successfully converted? 2. What is the purpose of exception handling? 3. When does the catch code block get executed? 4. Describe a C# statement that should be protected using exception handling. Computer Science Notes [5] Type Conversions and Exceptions