Session 5

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 23

DCIT 318

PROGRAMMING II

Session 5 – Exceptions & Exception


Handling, Reading & Writing Files
Lecturer: Mr. Paul Ammah, CSD
Contact Information: [email protected]

Department of Computer Science


School of Physical and Mathematical Sciences
2023/2024
Exceptions
• Exceptions in C# provide a structured, uniform, and type-safe
way of handling both system level and application-level error
conditions.
• Exceptions have the following properties:
– Exceptions are types that all ultimately derive from
System.Exception.
– Use a try block around the statements that might throw exceptions.
– If no exception handler for a given exception is present, the program
stops executing with an error message.
– If a catch block defines an exception variable, you can use it to
obtain more information about the type of exception that occurred.
– Exceptions can be explicitly generated by a program by using the
throw keyword.
Slide 2
Causes of Exceptions
• A throw statement throws an exception immediately
and unconditionally.
• Control never reaches the statement immediately
following the throw.
• Certain exceptional conditions that arise during the
processing of C# statements and expression cause an
exception in certain circumstances when the
operation cannot be completed normally
– Example: An integer division operation

Slide 3
The System.Exception class
• The System.Exception class is the base type of all
exceptions.
• This class has a few notable properties that all
exceptions share:
– Message is a read-only property of type string that
contains a human-readable description of the reason for
the exception.
– InnerException is a read-only property of type Exception.
If its value is non-null, it refers to the exception that caused
the current exception

Slide 4
Common Exceptions

Slide 5
Exception Handling
• A try block is used to partition code that might be
affected by an exception.
• Associated catch blocks are used to handle any
resulting exceptions.
• A finally block contains code that is run whether or
not an exception is thrown in the try block

Slide 6
Exception Handling cont’d
try
{
// Code to try goes here.
}
catch (SomeSpecificException ex)
{
// Code to handle the exception goes here.
// Only catch exceptions that you know how to handle.
// Never catch base class System.Exception without
// rethrowing it at the end of the catch block.
}

Slide 7
Exception Handling cont’d
try
{
// Code to try goes here.
}
finally
{
// Code to execute after the try block goes here.
}

Slide 8
Exception Handling cont’d
try
{
// Code to try goes here.
}
catch (SomeSpecificException ex)
{
// Code to handle the exception goes here.
}
finally
{
// Code to execute after the try (and possibly catch)
// blocks goes here.
}
Slide 9
Examples
int GetInt(int[] array, int index)
{
try
{
return array[index];
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine(
"Parameter index is out of range.");
}
}

Slide 10
Creating and Throwing Exceptions
• You create your own exception classes by deriving from
Exception
• The derived classes should define at least three
constructors:
– one parameterless constructor,
– one that sets the message property,
– and one that sets both the Message and InnerException
properties.
• Add new properties to the exception class when the data
they provide is useful to resolving the exception.
– ToString() should be overridden to return the added information.

Slide 11
Example: Defining Exception Classes
[Serializable]
public class InvalidDepartmentException : Exception
{
public InvalidDepartmentException() : base() { }

public InvalidDepartmentException(string message) :


base(message) { }

public InvalidDepartmentException
(string message, Exception inner) :
base(message, inner) { }
}

Slide 12
Throwing Exceptions
• Exception objects that describe an error are created and then thrown with the
throw statement or expression.

public class ProgramLog


{
FileStream logFile = null!;
public void OpenLog(FileInfo fileName, FileMode mode) { }

public void WriteLog()


{
if (!logFile.CanWrite)
{
throw new InvalidOperationException("Logfile cannot be
read-only");
}
// Else write data to the log and return.
}
}

Slide 13
Things to Avoid When Throwing Exceptions

• Do not use exceptions to change the flow of a


program as part of ordinary execution.
– Use exceptions to report and handle error conditions.
• Exceptions should not be returned as a return value
or parameter instead of being thrown.
• Do not throw System.Exception,
System.SystemException,
System.NullReferenceException, or
System.IndexOutOfRangeException intentionally from
your own source code.
Slide 14
Reading Files using StreamReader
using System.IO;
try {
StreamReader sr = new StreamReader("C:\\Sample.txt");
line = sr.ReadLine(); //read first line
while (line != null) {
Console.WriteLine(line);
line = sr.ReadLine();
} catch(Exception e) {
Console.WriteLine("Exception: " + e.Message);
} finally {
sr.Close();
Console.WriteLine("Executing finally block.");
}
Slide 15
StreamReader Class

Slide 16
Writing Files using StreamWriter
using System.IO;
try {
StreamWriter sw = new StreamWriter("C:\\Test.txt");
sw.WriteLine("Hello World!!");
sw.WriteLine("From the StreamWriter class");
sw.Close();
} catch(Exception e) {
Console.WriteLine("Exception: " + e.Message);
} finally {
Console.WriteLine("Executing finally block.");
}

Slide 17
Writing Files in Append Mode

//Open the File in append mode
StreamWriter sw = new
StreamWriter("C:\\Test1.txt", true);

//Write out the numbers 1 to 10 on the same line.


for(x=0; x < 10; x++) {
sw.Write(x);
}
//close the file
sw.Close();

Slide 18
StreamWriter Class

Slide 19
File Operations via using Keyword
• The using keyword has two major uses:
– The using directive creates an alias for a namespace or imports
types defined in other namespaces
• using System;
• using System.IO;
• The using statement defines a scope at the end of which an
object is disposed:
using (StreamWriter writer = new StreamWriter(filePath)) {
writer.WriteLine(textToWrite);
}

Slide 20
Reading with Using keyword
string line;
// Use the using statement to ensure the StreamReader
is // properly disposed of
using (StreamReader r = new StreamReader("numbers.txt"))
{
while (line = r.ReadLine()) {
Console.WriteLine(line);
}
}

Slide 21
Writing with Using keyword
string filePath = "example.txt";
string textToWrite = "Hello, this is a test message!";

// Use the using statement to ensure the StreamWriter


is // properly disposed of

using (StreamWriter writer = new StreamWriter(filePath)) {


writer.WriteLine(textToWrite);
}

Slide 22
THE END

Slide 23

You might also like