1T 104
MODULE 1
COMPUTER PROGRAMMING 2
MANAGING ERRORS AND EXCEPTIONS
MODULE GUIDE
In this chapter we will discuss errors and exceptions in C# programming in
particular. We will learn how to handle exceptions using the try-catch construct We will
also be learning on how C# uses exceptions to signal that an error has occurred and how
to use the try, catch, and finally statements to catch and handle the errors that these
exceptions represent.
At the end, we will look at the advantages of using exceptions, best practices and
how to apply them in different situations.
LEARNING PLAN
Intended Learning Outcomes:
• Identify and explain the different types of errors that are found in programs.
• Demonstrate correctly the use of exception-handling techniques.
Enabled Learning Outcomes
1. Understand the concept of errors and exceptions.
2. Apply exception-handling techniques in a program.
3. Create a C# programs that will use try and catch to handle exceptions.
SLSU CCSIT MAIN CAMPUS 1
1T 104
MODULE 1
COMPUTER PROGRAMMING 2
It is very difficult to ensure that a piece of code always works as expected. Failures
can occur for a large number of reasons, many of which are beyond your control as a
programmer. Any applications that you write must be capable of detecting failures and
handling them in a graceful manner, either by taking the appropriate corrective actions
or, if that is not possible, by reporting the reasons for the failure in the clearest possible
way to the user.
The Visual Studio integrated development environment (IDE) reports errors in
your program as soon as it is able to detect a problem. There are two major types of
errors: compiler or syntax errors and run-time errors.
Compiler or Syntax Errors
Compiler errors are the easiest to discover and eliminate. A compiler error is
associated with a language rule violation. C# has about 90 keywords, uses a curly brace
notation, and requires that statements end with a semicolon. C# adheres to a fairly
sophisticated set of rules known as C# Language Specifications, which are the
authoritative source for C# grammar and syntax. As long as you do not violate any rules,
no syntax errors are issued.
Run-Time Errors
Just because your program reports no syntax errors does not necessarily mean it
is running correctly. Sometimes a program stops during execution. Other times, output is
produced, but the output might not be correct. One form of run-time error is a logic error.
Logic errors are normally associated with programs that run but produce incorrect
results.
Errors can occur at almost any stage when a program runs. When something goes
wrong while a C# program is running, an exception occurs. Exceptions stop the current
flow of the program, and if nothing is done, the program simply stops running.
Exceptions can be caused by a bug in the program. As a programmer, you need to allow
your program to deal with these problems without crashing to a halt.
What Is an Exception?
Exception is a notification that something interrupts the normal program
execution. Exceptions provide a programming paradigm for detecting and reacting to
unexpected events. When an exception arises, the state of the program is saved, the
normal flow is interrupted and the control is passed to an exception handler (if such
exists in the current context).
When such unusual event takes place, the executing method ’throws' a special
object containing information about the type of the error, the place in the program where
the error occurred as well as the program state at the moment of the error.
Each exception in .NET contains the so-called stack trace, which gives information of where
exactly the error occurred.
SLSU CCSIT MAIN CAMPUS 2
1T 104
MODULE 1
COMPUTER PROGRAMMING 2
An Example Code Throwing an Exception during execution
Sample Output (when an exception occurs):
Catching and Handling Exceptions
• If a program encounters a run-time error, and the program cannot recover from
the error, it raises or throws an exception.
• When this happens, execution halts in the current method and the common
language runtime (CLR) attempts to locate an exception handler to handle the
exception.
• An exception handler is a block of code that is executed when an exception
occurs.
C# provides several keywords — try, catch, and finally — that allow programs to
detect exceptions, deal with them, and continue running. They are a very useful tool for
making your applications more reliable.
The try and catch keywords are used together. Use try to enclose the block of code
you are concerned might generate an exception, and catch to contain the code that will
be executed if the exception occurs.
SLSU CCSIT MAIN CAMPUS 3
1T 104
MODULE 1
COMPUTER PROGRAMMING 2
C# try and catch Programming Construct
• To handle an exception, we must surround the code that could throw an exception
with a try-catch block
• try – a try statement allows you to define a block of code to be tested for errors
while it is being executed.
• catch – a catch statement allows you to define a block of code to be executed, if an
error occurs in the try block. The catch keyword indicates the catching of
an exception.
• finally − the finally block is used to execute a given set of statements, whether an
exception is thrown or not thrown.
Try and Catch syntax:
Take Note:
• try and catch are always use in pair.
• A try block must include at least one catch clause.
• More than one catch clause can also be included.
• Notice that a square bracket follows the keyword catch to indicate that
the parentheses and the argument list are optional.
• Omitting the argument list makes the catch generic—meaning any
exception that is thrown is handled by executing the code within that
catch block.
• If you include an exception type as part of the argument list, only
exceptions that match the type listed are handled by that catch clause.
• finally is enclosed with square bracket which indicates that this block is
optional to use in a try-catch program construct.
SLSU CCSIT MAIN CAMPUS 4
1T 104
MODULE 1
COMPUTER PROGRAMMING 2
Example Program 1:
Sample Output:
Example Program 2:
Create a C# program that will ask the user to input two numbers, Computer and
display the sum and average of the two numbers. Use the try and catch method to ensure
that the program will accept numeric values only. If wrong input, display ("You input an
invalid number!").
SLSU CCSIT MAIN CAMPUS 5
1T 104
MODULE 1
COMPUTER PROGRAMMING 2
Sample Outputs:
Example Program 3: (using a specific catch exception handler)
SLSU CCSIT MAIN CAMPUS 6
1T 104
MODULE 1
COMPUTER PROGRAMMING 2
Sample Output:
Example Program 4: (using multiple catch exception handler)
SLSU CCSIT MAIN CAMPUS 7
1T 104
MODULE 1
COMPUTER PROGRAMMING 2
Sample Outputs:
Exception Classes in C#
C# exceptions are represented by classes. The exception classes in C# are mainly
directly or indirectly derived from the [Link] class. Some of the exception
classes derived from the [Link] class are the [Link]
and [Link] classes.
The [Link] class supports exceptions generated by
application programs. Hence the exceptions defined by the programmers should derive
from this class.
The [Link] class is the base class for all predefined system
exception.
SLSU CCSIT MAIN CAMPUS 8
1T 104
MODULE 1
COMPUTER PROGRAMMING 2
The following table provides some of the predefined exception classes derived from the
[Link] class −
[Link]. Exception Class & Description
1
[Link]
Handles I/O errors.
2
[Link]
Handles errors generated when a method refers to an array index out of
range.
3
[Link]
Handles errors generated when type is mismatched with the array type.
4
[Link]
Handles errors generated from referencing a null object.
5
[Link]
Handles errors generated from dividing a dividend with zero.
6
[Link]
Handles errors generated during typecasting.
7
[Link]
Handles errors generated from insufficient free memory.
8
[Link]
Handles errors generated from stack overflow.
SLSU CCSIT MAIN CAMPUS 9
1T 104
MODULE 1
COMPUTER PROGRAMMING 2
REFERENCES
1. Stephens,R. (2014). C# 5.0 Programmer’s Reference. John Wiley & Sons,
Inc.
2. Nakov, S., & Kolev, V. (2013). Fundamentals of Computer Programming
with C#: The Bulgarian C# Book. Faber Publishing.
3. Sharp, J. (2015). Microsoft Visual C# Step by Step, 8th Edition. Microsoft
Press
4. Learn C# Programming [internet]: c 2022.
Available from: [Link]
5. C# Tutorial [internet]:C1999-2023.
Available from: [Link]
SLSU CCSIT MAIN CAMPUS 10