You are on page 1of 13

BAHIR DAR UNIVERSITY

BAHIR DAR INSTITUTE OF TECHNOLOGY


FACULTY OF COMPUTING
ITBED DEPARTEMENT
EVENT DRIVEN GROUP ASSIGNEMENT

Name----------------------------------------------ID
1.Tadesse Birhanu.......................................1306759
2.Sewunet Belay...........................................1311172
3.Selemon Gebre..........................................1307757
4. Mekdes Tekalign......................................1308668
5.Asmera Dagne………………………1309085
6.Habtamu Tesema……………………1306272

Submitted to: Mr. Ababayew


Submission date: 24/07/2016 E.C
Bahir Dar, Ethiopia
Exception
In C#, an exception is an object that represents an error or exceptional condition
that occurs during the execution of a program. Exceptions are used to handle
unexpected situations gracefully and prevent the program from crashing. C#
provides a robust exception handling mechanism that allows developers to catch
and handle exceptions in a structured way.
Exception Types: C# has a hierarchy of exception types, with the base type being
System.Exception. This base type is further subclassed into various specific
exception types, such as System.NullReferenceException,
System.DivideByZeroException, System.IndexOutOfRangeException, and many
others. Each exception type represents a different kind of error or exceptional
condition.
Throwing Exceptions: Exceptions are thrown using the throw keyword followed
by an instance of an exception object. For example, to throw a
DivideByZeroException, you can use:
throw new DivideByZeroException("Cannot divide by zero.");
You can also create custom exception types by deriving from System.Exception or
any of its subclasses.
Catching Exceptions: Exceptions are caught and handled using try-catch blocks.
A try block contains the code that may potentially throw an exception, while one or
more catch blocks handle specific types of exceptions that may occur.
Additionally, you can have a finally block that executes cleanup code regardless of
whether an exception occurred.
try
{
// Code that may throw an exception
int result = Divide(10, 0); // Potential division by zero error
Console.WriteLine(result);
}
catch (DivideByZeroException ex)

1
{
// Handle specific exception
Console.WriteLine("Error: " + ex.Message);
}
catch (Exception ex)
{
// Handle other exceptions
Console.WriteLine("An error occurred: " + ex.Message);
}

finally
{
// Cleanup code
// This block will always execute, whether an exception occurred or not
}
Exception Propagation: If an exception is thrown within a method and not caught
within that method, it propagates up the call stack until it is caught by an
appropriate catch block or until it reaches the top-level exception handler, which
may terminate the program.
Handling Unhandled Exceptions: In C#, unhandled exceptions at the top level of
the application can be caught and logged using mechanisms like the
AppDomain.UnhandledException event or the
TaskScheduler.UnobservedTaskException event in asynchronous code.
Default exception
In C#, the default exception is the System.Exception class. This class serves as the
base class for all exceptions in C#. It provides properties and methods that are
common to all exceptions, such as the Message property (which contains a human-

2
readable description of the error) and the StackTrace property (which contains
information about the call stack at the time the exception was thrown).
When you create custom exception classes in C#, you typically derive them from
System.Exception.
For example:
public class CustomException : Exception
{
public CustomException(string message) : base(message)
{
}
}
In this example, CustomException is a custom exception class that inherits from
System.Exception. It adds no new functionality but can be used to represent
specific types of errors or exceptional conditions within your application.
It's important to note that while System.Exception is the default base class for
exceptions, there are also other built-in exception classes provided by the .NET
Framework that you can use for specific types of errors. Some common built-in
exception classes include:
System.NullReferenceException: Thrown when attempting to dereference a null
object reference.
string str = null;
int length = str.Length; // This will throw a NullReferenceException
System.DivideByZeroException: Thrown when attempting to divide an integer or
decimal number by zero.
int result = 10 / 0; // This will throw a DivideByZeroException
System.IndexOutOfRangeException: Thrown when accessing an array or
collection with an index that is outside the valid range.
int[] numbers = new int[5];
int value = numbers[10]; // This will throw an IndexOutOfRangeException

3
System.IO.IOException: Thrown for input/output related errors, such as file not
found or access denied.
try
{
File.Open("nonexistentfile.txt", FileMode.Open);
}
catch (IOException ex)
{
Console.WriteLine("An IO exception occurred: " + ex.Message);
}
System.ArgumentException: Thrown when an argument to a method is invalid.
These built-in exception classes inherit from System.Exception and provide more
specific information about the type of error that occurred, making it easier to
handle different types of exceptions in your code.
int age = -5;
if (age < 0)
{
throw new ArgumentException("Age cannot be negative");
}

Exception handling
Exception handling, also known as error handling or exceptional handling, is a
programming technique used to manage and respond to unexpected or exceptional
conditions that occur during the execution of a program. These exceptional
conditions, often referred to as exceptions, can include errors such as division by
zero, file not found, network connection failures, and many others.
Exception handling aims to ensure that when such exceptional conditions occur,
the program can respond in a controlled and graceful manner, rather than crashing

4
or producing unpredictable results. The key aspects of exceptional handling
include:
Throwing Exceptions: When an exceptional condition occurs within a method or
block of code, an exception is thrown using the throw keyword followed by an
instance of an exception object. For example:
if (divisor == 0)
{
throw new DivideByZeroException("Cannot divide by zero.");
}
Catching Exceptions: To handle exceptions, developers use try-catch blocks. A
try block contains the code that may potentially throw an exception, while one or
more catch blocks handle specific types of exceptions that may occur. For
example:
try
{
int result = Divide(10, 0); // Potential division by zero error
Console.WriteLine(result);
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Error: " + ex.Message);
}
Finally Block: Optionally, a try-catch block can be followed by a finally block,
which contains code that is executed regardless of whether an exception occurs.
The finally block is often used for cleanup operations such as closing files or
releasing resources.

5
try
{
// Code that may throw an exception
}
catch (Exception ex)
{
// Handle exception
}
finally
{
// Cleanup code
}
Exception Propagation: If an exception is thrown within a method and not caught
within that method, it propagates up the call stack until it is caught by an
appropriate catch block or until it reaches the top-level exception handler.
Custom Exceptions: Developers can create custom exception types by deriving
from the base System.Exception class or its subclasses. Custom exceptions can be
used to represent specific types of errors or exceptional conditions within an
application.
Exception handling is a critical aspect of writing robust and reliable software. It
helps developers identify and address potential problems, ensures proper resource
management, and improves the overall stability and usability of software
applications.

Error
In C#, an "error" refers to any mistake, fault, or unexpected condition that occurs
during the development or execution of a program, which prevents the program
from functioning as intended. Errors can occur at different stages, including
compile-time (static errors) and runtime (dynamic errors).
The main types of errors in C#:

6
1.Compile-Time Errors:
Syntax Errors: These errors occur when the code violates the syntax rules of
the programming language. For example, missing semicolons, mismatched
parentheses, or using reserved keywords as identifiers.
Type Errors: These errors occur when there is a mismatch between data types,
such as trying to assign a string value to an integer variable.
// Example of compile-time errors
int x = "hello"; // Type mismatch error
Console.WriteLine("Hello, world!" // Missing semicolon

2.Runtime Errors:
Null Reference Exceptions: These errors occur when trying to access members
or methods of a null object reference.
Divide By Zero Exceptions: These errors occur when attempting to divide a
number by zero.
Index Out Of Range Exceptions: These errors occur when trying to access
elements outside the bounds of an array or collection.
// Example of runtime errors
int y = 10 / 0; // Division by zero error
int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers[5]); // Index out of range error

3.Logical Errors:
Logic errors occur when the program runs without crashing but produces incorrect
results due to flawed logic or incorrect algorithms. These errors are often harder to
detect and may require debugging to identify and fix.
// Example of logical error
int sum = 0;
for (int i = 1; i <= 10; i++)
{

7
sum += i; // This should be sum *= i for factorial calculation
}
Console.WriteLine("Sum: " + sum); // Incorrect sum due to logic error

User define error


In C#, a user-defined error refers to an error or exception that you create and define
yourself, rather than using one of the built-in exception classes provided by
the .NET Framework. User-defined errors are useful for representing specific types
of errors or exceptional conditions within your application that are not covered by
the standard exception classes.
To define a user-defined error in C#, you typically create a custom exception class
that inherits from the System.Exception class or one of its derived classes. Here's
an example of how you can define a user-defined error in C#: using System;
// Define a custom exception class
public class CustomException : Exception
{
// Constructor that takes a message parameter
public CustomException(string message) : base(message)
{
}
// You can add additional properties or methods as needed
}
In the above example: We create a new class called CustomException that inherits
from System.Exception.
We provide a constructor that takes a string parameter message and passes it to the
base class constructor (base(message)). This allows us to initialize the Message
property of the exception with a custom error message.
Once you have defined your custom exception class, you can throw instances of
this class in your code to represent specific user-defined errors. Here's an example
of how you might use the CustomException class:

8
public class MyClass
{
public void DoSomething(int value)
{
if (value < 0)
{
throw new CustomException("Value must be greater than or equal to 0.");
}
// Perform some operation here
}
}
In this example, the DoSomething method checks if the value parameter is less
than zero. If it is, it throws a CustomException with a custom error message
indicating that the value must be greater than or equal to zero.

Error handling
In C#, errors are typically handled using exception handling mechanisms provided
by the language. Exception handling allows you to gracefully manage unexpected
or exceptional conditions that may occur during the execution of your program,
preventing it from crashing and allowing you to handle errors in a structured way.
Here's how you can handle errors in C# using exception handling:
Throwing Exceptions:
When an error occurs within your code that you want to handle, you can throw an
exception using the throw keyword followed by an instance of an exception object.
Throwing an Exception
If you want to throw your own Exception (e.g. force an exception in your code)
then you can use the throw keyword. For example to manually throw your own
exception you could use
class MainProgram

9
{
static void Main(string[] args)
{
string fileContents;
string path = "C:\\test.txt"; // file that doesn't exist

try
{
if (File.Exists(path))
{
fileContents = System.IO.File.ReadAllText(path);
Console.WriteLine(fileContents);
}
else
{
throw new Exception("My file was not found");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}

10
In this example the throw new statement creates an Exception object from the base
'Exception' class. If we look at the definition for the 'Exception' class we can see
that this class can accept a 'string' that is the message
Catching Exceptions:
To handle exceptions, you use try-catch blocks. A try block contains the code that
may potentially throw an exception, while one or more catch blocks handle
specific types of exceptions that may occur.
try
{
int result = Divide(10, 0); // Potential division by zero error
Console.WriteLine(result);
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Error: " + ex.Message);
}
In this example, if a DivideByZeroException is thrown inside the try block (e.g.,
due to division by zero in the Divide method), it will be caught by the
corresponding catch block where you can handle the error.
Finally Block:
Optionally, you can use a finally block after the try-catch blocks to include cleanup
code that should execute regardless of whether an exception occurred or not. This
is often used for resource cleanup, such as closing files or releasing resources.
try
{
// Code that may throw an exception
}
catch (Exception ex)

11
{
// Handle exception
}
finally
{
// Cleanup code
}
Custom Exceptions:
You can also create custom exception types by defining a new class that inherits
from System.Exception or any of its subclasses. Custom exceptions can be used to
represent specific types of errors or exceptional conditions within your application.
public class CustomException : Exception
{
public CustomException(string message) : base(message)
{
}
}
You can then throw and catch instances of your custom exception class similar to
built-in exceptions.
Exception handling in C# is essential for writing robust and reliable applications. It
allows you to anticipate and manage errors effectively, improving the overall
stability and user experience of your software.

12

You might also like