0% found this document useful (0 votes)
6 views28 pages

Exception Handling and Debugging

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views28 pages

Exception Handling and Debugging

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 28

Chapter 4

Exception Handling and debugging

1
Introduction to exception handling

• What is an exception? Exceptions are exceptional events or error conditions


within an application and are categorized as System or application
exceptions.
System exceptions are raised by the Common Language Runtime (CLR) and
include null reference, out of memory, divide by zero, and stack overflow
exceptions.
Application exceptions are custom exceptions, are thrown by the application, not
by the CLR. Some exceptional events or error conditions are detectable by
application logic, not by the runtime. 2
Causes of Exception
• Errors. Errors are the triggering events for Exceptions to occur.

•What is debugging ?
• The process of trying to track down errors in your program.
• It can also refer to handling any potential errors that may occur.
•There are three types of errors are Design-time errors, Run-time errors
and Logical errors

3
A. Design-time errors
Design-Time errors are ones that you make before the program even runs.

In fact, for Design-Time errors, the program won’t run at all, most of the
time.

 You’ll get a popup message telling you that there were build errors, and
asking would you like to continue.

 Design-Time errors are easy enough to spot because the C# software will
underline them with a wavy colored line.

12/26/24 4
colored lines to show design
time errors
The blue wavy lines are known as Edit and Continue issues, meaning
that you can make change to your code without having to stop the
program altogether.
Red wavy lines are Syntax errors, such as a missing semicolon at the
end of a line, or a missing curly bracket in an IF Statement.
Green wavy lines are Compiler Warnings. You get these when C#
spots something that could potentially cause a problem, such as
declaring a variable that’s never used. 5
B. Run-Time Errors
Run-Time errors are ones that crash your program.
 The program itself generally starts up OK.
 It’s when you try to do something that the error surfaces.
 A common Run-Time error is trying to divide by zero.

6
C. Logic Errors
Logic errors are ones where you don’t get the result you were
expecting. Errors in programming logic
The program generally won’t “bug out” on you.

12/26/24 7
• What is Exception handling? Its mechanism to handle errors happened in
programming lanagueg and is an important ingredient of a robust application and
should be included in the application design of every .NET program.

• Exception handling helps applications identify and respond to exceptional events in


a known and robust manner.

• This enhances the correctness of an application, which naturally improves customer


satisfaction.

• Unfortunately, exception handling is often an afterthought, which leads to poorly


implemented solutions for exception handling and a less robust application.

• Starting with application design, exception handling should be included in all


aspects of application planning and development. 8
Structured Exception Handling
.NET advocates structured exception handling, which is essentially the
try and catch statements.
A structured exception evaluates the stack to determine when code is
protected and where an exception is caught and handled.
When exceptions occur, the stack is walked in search of an exception
handler.
When a matching catch filter is located, the exception is handled in the
exception handler, which is the catch block. 9
Exampleusing
: System;
public class ExceptionHandling {
public static void Main ( ) {
try {
int var1=5, var2=0;
var1/=var2;
} catch (DivideByZeroException et) {
Console.WriteLine("Exception "+et.Message);
}catch(System.ArithmeticException e1) {
Console.WriteLine("Exception "+e1.Message);
}catch(Exception e2)
{
Console.WriteLine("Exception "+e2.Message);
}
Console.ReadKey();
static void Main(string[] args) {
Console.WriteLine(var1);
Console.ReadKey();
} } }
10
CH 5 File maniplutaing

• Introduction
• How to open a Text File
• Read from a Text file
• Write to a Text File
• How to Copy, Move and Delete a File
11
Introduction
File is a collection of data stored in a disk with a specific name and a
directory path.
When a file is opened for reading or writing, it becomes a stream.

Stream is sequence of bytes passing through the communication path.

There are two main streams:

1.Input Stream: is used for reading data from file (read operation)

2.Output Stream: is used for writing into the file (write operation).
12
C# I/O Classes
System.IO namespace has various classes that are used for
performing numerous operations with files,
This file operations include;

• Creating and deleting files,


• Reading from or writing to a file,
• Opening and closing a file etc.

13
Commonly used non-abstract classes in the System.IO
I/O Class Description
namespace
BinaryReader Reads primitive data from a binary stream.
BinaryWriter Writes primitive data in binary format.

BufferedStream A temporary storage for a stream of bytes.


Directory Helps in manipulating a directory structure.
DirectoryInfo Used for performing operations on directories.

DriveInfo Provides information for the drives.

File Helps in manipulating files.

FileInfo Used for performing operations on files.


14
I/O Class Description

FileStream Used to read from and write to any location in a file.

MemoryStream Used for random access to streamed data stored in memory.

Path Performs operations on path information.

StreamReader Used for reading characters from a byte stream.


StreamWriter used for writing characters to a stream.

StringReader used for reading from a string buffer.

StringWriter used for writing into a string buffer.

15
General file Manipulating
methods
Checking if a file exists
if(File.Exists("MyFile.txt"))
{
Console.WriteLine("File exist");
}
else
{
Console.WriteLine("File does not exist");
}

16
Cont’d…
Creating a new file
File.Create(FILE_DIR + "MyFile.bin");
Copying a file
File.Copy("MyFile.txt","MyFile2.txt",true);
Note the third argument in the above Copy method is used to indicate
whether the [second] file should be overwritten or not if it already
exists.

17
Cont’d…
Delete a file
File.Delete("MyFile2.txt");

Moving a file
File.Move("MyFile.txt","MySubDir\\MyMovedFile.txt");

18
Text files
Writing text to a text file
StreamWriter myFile = File.CreateText("MyFile.txt");
myFile.WriteLine("This text will be stored in a text file");
myFile.Close();
Appending text to a text file
StreamWriter myFile = File.AppendText("MyFile.txt");
myFile.WriteLine("This text will be appended to the file");
myFile.Close();
19
Text files
Reading from a text file
string s;
StreamReader myFile = File.OpenText("MyFile.txt");
while ((s = myFile.ReadLine()) != null)
{
Console.WriteLine(s);
}
myFile.Close();
Event Driven Programming Chapter-5:
12/26/24 20
File Manipulation
Classes File and Directory

Classes File and Directory allow an application to obtain


information about files and directories stored on disc
Each class contains a large set of static methods for both
manipulation and information gathering
These classes could be the basis of a hard disc scanning application
to determine usage and the amount of available storage space

21
Classes File and
Directory
static Method Description

AppendText Returns a StreamWriter that appends text


to an existing file or creates a file if one does
not exist.
Copy Copies a file to a new file.
Create Creates a file and returns its associated
FileStream.
CreateText Creates a text file and returns its associated
StreamWriter.
Delete Deletes the specified file.
Exists Returns true if the specified file exists and
false otherwise.
GetCreationTime Returns a DateTime object representing when
the file was created.

GetLastAccessTime Returns a DateTime object representing


when the file was last accessed.

Static methods of File


Event Driven Programming Chapter-5:
12/26/24 22
File Manipulation
Classes File and
Directory
static Method Description

GetLastWriteTime Returns a DateTime object representing


when the file was last modified.
Move Moves the specified file to a specified location.
Open Returns a FileStream associated with the
specified file and equipped with the specified
read/write permissions.
OpenRead Returns a read-only FileStream associated
with the specified file.
OpenText Returns a StreamReader associated with the
specified file.
OpenWrite Returns a read/write FileStream associated
with the specified file.

Static methods of File (cont..)


Event Driven Programming Chapter-5:
12/26/24 23
File Manipulation
Classes File and Directory
static Method Description

CreateDirectory Creates a directory and returns its associated


DirectoryInfo object.
Delete Deletes the specified directory.
Exists Returns true if the specified directory exists and
false otherwise.
GetDirectories Returns a string array containing the names of
the subdirectories in the specified directory.
GetFiles Returns a string array containing the names of
the files in the specified directory.
GetCreationTime Returns a DateTime object representing when the
directory was created.
GetLastAccessTime Returns a DateTime object representing when the
directory was last accessed.
GetLastWriteTime Returns a DateTime object representing when
items were last written to the directory.
Move Moves the specified directory to a specified
location.

12/26/24
Static methods of Directory 24
Event Driven Programming Chapter-5:
12/26/24 25
File Manipulation
using System;
using System.Windows.Forms;
using System.IO;

public partial class FileTestForm1 : Form


{
public FileTestForm1()
{ InitializeComponent(); }

private void openFileDialog1_FileOk(object sender, CancelEventArgs e)


{
string fileName = openFileDialog1.FileName;
if (File.Exists(fileName))
displayFileInfo(fileName);
}

private void displayFileInfo(string fileName)


{ // Displays file information }

private void displayDirectoryInfo(string pathName)


{ // Displays directory information }

private void button1_Click(object sender, EventArgs e)


{ openFileDialog1.ShowDialog(); }

private void button2_Click(object sender, EventArgs e)


{
folderBrowserDialog1.ShowDialog();
string pathName = folderBrowserDialog1.SelectedPath;
if (Directory.Exists(pathName))
displayDirectoryInfo(pathName);
}
}
12/26/24 26
Classes File and Directory
private void displayFileInfo(string fileName)
{
outputTextBox.Text += "\r\n\r\nFile: " + fileName + ":\r\n";
DateTime creationTime = File.GetCreationTime(fileName);
outputTextBox.Text += "Created: " + creationTime.ToString() + "\r\n";
DateTime lastModifiedTime = File.GetLastAccessTime(fileName);
outputTextBox.Text += "Last accessed: " + lastModifiedTime.ToString() +
"\r\n";
}

private void displayDirectoryInfo(string pathName)


{
string[] directoryList;
directoryList = Directory.GetDirectories(pathName);
outputTextBox.Text += "\r\n\r\nDirectory Contents:\r\n";

// Output directory contents


for (int i = 0; i < directoryList.Length; i++)
outputTextBox.Text += directoryList[i] + "\r\n";
}

27
Thank
you!
28

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy