You are on page 1of 26

Module 1

Exceptions and File IO

1
Learning Objectives
• Use try, catch, and finally blocks to implement exception handlers
• Practice writing to a text file in a console application
• Practice reading from a text file in a console application
• Develop a Unity game that reads and uses game configuration data
from a csv file

2
Content (Slot 1)
• Exceptions
• Exercise 1

3
Content (Slot 2)
• Streams
• Text Files
• Files of Objects
• PlayerPrefs Class
• Game Configuration Storage

4
Exceptions
• A program you wrote will “blow up” – if you try to call a method on
an object you haven’t yet created, for example.
• C# throws an exception, which then terminates the program.
• To keep our program from terminating because of the exception, we
can handle (or catch) that exception by using an exception handler.
• We can also explicitly throw exceptions in our code as necessary.
• Although our Unity games don't typically terminate when exceptions
are thrown, we can see those exceptions getting thrown in the
Console window as our game runs. Because this is an indication of a
problem in our game, those exceptions need to be fixed or handled as
well. 5
Exceptions
• The key idea behind all this is that our programs throw exceptions when
something unusual happens that has significant negative effects on the
program’s ability to continue executing correctly.
• Exceptions aren’t about “business as usual,” they’re for taking care of
unusual circumstances.

6
Exceptions
• The following code to divide two numbers provided by the user:

• What happens if the user doesn’t enter a number, though? The code (the
Parse method) will throw an exception – specifically, a FormatException –
and terminate the program.
7
Exceptions

8
Exceptions

9
Exceptions

• If either of the calls to the Parse method throws a FormatException, the


program immediately goes to the catch block to execute the code in that
block.
• If all of the code in the try block executes without throwing an exception,
the program simply skips all the catch blocks after the try block code is
done and proceeds to the code following the exception handler.
• That solves our immediate problem (catching the thrown exception), but if
this exception does get thrown, we probably want to give the user an
opportunity to retry their input.

10
Exceptions

Exception Handling for Input Validation

11
Exceptions
Exception Handling for Input Validation

12
Exceptions
Exception Handling for Input Validation
• This solves our immediate problem – the user can’t crash the code by
entering a string – but if they enter a string the catch block executes and
they don’t get a chance to try another input.
• We need the exception handler to be contained inside a loop to make this
happen.
• Conceptually, we need to loop while the user hasn’t provided a valid
input, so let’s use a Boolean flag to tell whether the user has provided
valid input.

13
Exceptions

14
Exceptions
Exception Handling for Input Validation
• There are a couple of things we can clean up in the code.
• For example, the code in the previous slide prompts for and reads in the GPA
is included twice.
• It’s also a little confusing understanding when the flag gets set to true. We can
certainly figure that out, but we can make that clearer as well.
• The code in the next slide provides final solution.

15
Exceptions
• Exception Handling for Input Validation

16
Exceptions
Multiple Catch Blocks
• the double Parse method can actual throw three different exceptions:
ArgumentNullException (if the string we’re parsing is null),
FormatException (which we’ve already discussed), and OverflowException
(if the number is too small or too large to fit into a double).
• In the previous example, it’s impossible for a null string to be parsed,
because if the user just presses the Enter key we read in an empty string (a
string with no characters in it) rather than a null string.
• Use multiple Catch blocks to print a different message for each of the
other two exceptions above.

17
Exceptions
Multiple Catch Blocks

18
Exceptions
Multiple Catch Blocks

19
Exceptions
Multiple Catch Blocks
• Catch blocks work much like the if and else if blocks in an if statement. The
first block that matches the exception that was thrown is the block that’s
executed, then the code proceeds to the finally block (if there is one) or
out of the exception handler.
• The OverflowException catch block is the same as the error message if the
user enters a valid number but it’s out of range. The user can be given an
error message that makes sense to them without requiring that they
understand the valid ranges for C# data types.

20
Exceptions
Throwing Exceptions
• Let’s say we wanted to have the user enter a date in the format
mm/dd/yyyy. There’s actually a lot of work we’d need to go through to
check that format, but for this example, we’ll just make sure the string the
user enters contains two / characters. While there are really clean ways to
do this (using something called regular expressions, which are beyond the
scope of this book), we’ll use the approach shown in the next slide.

21
Exceptions
Throwing Exceptions

22
Exceptions
Throwing Exceptions

23
Exceptions
User-Defined Exceptions
• C# provides a class hierarchy with a number of useful pre-defined
exceptions in the hierarchy. The Exception class is the base (root) class for
all exceptions in that hierarchy.
• If none of the pre-defined exceptions are exactly what you want, you can
define a new exception class yourself.
• The only constraint is that you should make the Exception class the parent
class for your new class.

24
Exceptions
User-Defined Exceptions

• Because your new exception class inherits the fields and methods from the
Exception class, you can throw and handle your new exception just as we’ve been
doing all along. 25
Exercise 1: The User is Crazy!
• View LMS

26

You might also like