0% found this document useful (0 votes)
10 views32 pages

T2 Chương 3 - Exception Handling, Memory - C#

This document discusses exception handling and memory management mechanisms in C#. It covers topics such as the definition of exceptions, syntax for handling them, the System.Exception class, custom exceptions, and garbage collection in C#. Additionally, it provides best practices for memory management and examples of exception handling in C# programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views32 pages

T2 Chương 3 - Exception Handling, Memory - C#

This document discusses exception handling and memory management mechanisms in C#. It covers topics such as the definition of exceptions, syntax for handling them, the System.Exception class, custom exceptions, and garbage collection in C#. Additionally, it provides best practices for memory management and examples of exception handling in C# programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Chap 3.

Exception Handling,
memory management mechanism in C#
Ph.D. Luu Thi Bich Huong

@CMC UNI 2024


Content
3.1. Exception Handling
3.2. Memory management mechanism

@CMC UNI 2024


3.1. Exception Handling
1. What is exception?
2. Syntax
3. System.Exception class
4. Custom Exception
5. Hierachy Exception
6. Catch order
7. Rethrowing Exception
8. Final block

@CMC UNI 2024


What is Exception?
◆ Exceptions are errors that occur during program execution. They can
happen for a variety of reasons, such as invalid input or unexpected
behavior. When an exception occurs, it interrupts the normal flow of the
program and jumps to a special block of code called an exception
handler.
◆ In C#, exceptions are represented by objects that contain information
about the error, including its type, message, and stack trace. Exception
handling in C# involves writing code that can catch and handle these
objects when they are thrown. This is typically done using try-catch
blocks, which allow you to specify code to be executed if an exception of
a particular type is thrown.

@CMC UNI 2024


Example: Divided by zero
public class ExceptionTest
try
{
{
static double SafeDivision(double x, double y) result = SafeDivision(a, b);
{ Console.WriteLine("{0} divided by {1} =
{2}", a, b, result);
if (y == 0) }
throw new DivideByZeroException(); catch (DivideByZeroException)
return x / y; {
Console.WriteLine("Attempted divide
} by zero.");
public static void Main() }
}
{
}
// Input for test purposes. Change the values to see
// exception handling behavior.
double a = 98, b = 0;
double result;

@CMC UNI 2024


Syntax
try {
//statements causing exception
} catch (ExceptionName e1) {
//error handling code
}catch (ExceptionName e2) {
//error handling code
}catch (ExceptionName eN) {
//error handling code
} finally {
//statements to be exceptied
}

@CMC UNI 2024


Exceptions in .NET
try − A try block identifies a block of code for which particular exceptions
is activated. It is followed by one or more catch blocks.
catch − A program catches an exception with an exception handler at
the place in a program where you want to handle the problem. 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. For example, if you open
a file, it must be closed whether an exception is raised or not.
throw − A program throws an exception when a problem shows up. This
is done using a throw keyword.

@CMC UNI 2024


System.Exception
System.Exception is a base class for all exceptions in .NET

@CMC UNI 2024


System.Exception
• Characteristics:
• A classic implementation of OOP exception model
• Deliver powerful mechanism for centralized handling of
errors and unusual events
• Substitute procedure-orientated approach, in which
each function returns error code
• Simplify code constructions and maintenance
• Allow the problematic situations to be processed at
multiple levels
@CMC UNI 2024
System.Exception
System.Exception provides information about the cause of the
error or unusual situation via properties:
• Message – text description of the exception
• StackTrace – a snapshot of the stack at the moment the exception
is thrown
• InnerException – an exception that caused the current exception
(if any)

@CMC UNI 2024


Custom Exceptions
.NET provides a hierarchy
of exception classes
ultimately derived from
the Exception base class.
However, if none of the
predefined exceptions
meet your needs, you can
create your own
exception classes by
deriving from the
Exception class

@CMC UNI 2024


Custom Exceptions
using System; // Your custom validation logic goes here

// Step 1: Define your custom exception by inheriting from System.Exception // ...


class CustomValidationException : Exception
Console.WriteLine("Custom validation passed successfully."); }
{
// Step 2: Create any necessary constructors to customize the exception static void Main()
message {
public CustomValidationException() : base("Custom validation failed.")
{ } try

public CustomValidationException(string message) : base(message) {


{ }
Console.Write("Enter a positive number: ");
public CustomValidationException(string message, Exception innerException)
: base(message, innerException) int userInput = int.Parse(Console.ReadLine());
{ } } PerformCustomValidation(userInput);
class Program
}
{
// Step 3: Create a method that throws your custom exception catch (FormatException)
static void PerformCustomValidation(int value)
{ Console.WriteLine("Invalid input. Please enter a valid
{ if (value <= 0) number."); }
{
catch (CustomValidationException ex)
// Step 4: Throw your custom exception when the validation fails
throw new CustomValidationException("Value must be greater than 0."); {
} // Step 5: Catch and handle your custom exception

Console.WriteLine("Custom validation error: " + ex.Message);

} } }

@CMC UNI 2024


Hierachy Exceptions
When catching an exception of a particular class all derived
exceptions are caught too.
Example:

@CMC UNI 2024


Catch order
Order catch blocks from specific to general

@CMC UNI 2024


How exception works

@CMC UNI 2024


Rethrowing Exceptions
• You can explicitly throw an exception using the C#
throw or the Visual Basic Throw statement. You can
also throw a caught exception again using the throw
statement. It's good coding practice to add information
to an exception that's rethrown to provide more
information when debugging.

@CMC UNI 2024


Rethrowing Exceptions

The following code example uses a try/catch block to catch


a possible FileNotFoundException. Following the try block
is a catch block that catches the FileNotFoundException
and writes a message to the console if the data file is not
found. The next statement is the throw statement that
throws a new FileNotFoundException and adds text
information to the exception.

@CMC UNI 2024


Rethrowing Exceptions

var fs = default(FileStream);
try
{// Opens a text tile.
fs=new FileStream(@"C:\temp\data.txt", FileMode.Open);
var sr = new StreamReader(fs);
// A value is read from the file and output to the console.
string? line = sr.ReadLine();
Console.WriteLine(line);
}
catch (FileNotFoundException e)
{
Console.WriteLine($" [Data File Missing] {e}");
throw new FileNotFoundException(@"[data.txt not in c:\temp directory]", e);
}
finally
{if (fs != null)
fs.Close();
}

@CMC UNI 2024


Final-block
When an exception occurs, execution stops and control is
given to the appropriate exception handler. This often means
that lines of code you expect to be executed are bypassed.
Some resource cleanup, such as closing a file, needs to be
done even if an exception is thrown. To do this, you can use
a finally block. A finally block always executes, regardless of
whether an exception is thrown.

@CMC UNI 2024


Excercise
Exercise 1: Custom Validation Exception
Write a C# program that takes a student's age as input and
checks if it meets the eligibility criteria for admission to a
university. The criteria are as follows:

• The student's age must be between 18 and 25 (inclusive) to


be eligible for admission.
• If the age is not within this range, throw a custom exception
called AgeOutOfRangeException.

@CMC UNI 2024


Excercise
Exercise 2: Bank Account Exception Handling
Write a C# program to simulate a simple bank account. Create a
BankAccount class with methods to deposit and withdraw funds, and
a property to get the account balance. Handle the following
exceptions:

• If an attempt to withdraw results in a negative balance, throw a


custom exception called InsufficientFundsException.
• If an attempt to deposit or withdraw with a negative amount, throw
a custom exception called NegativeAmountException.

@CMC UNI 2024


3.2. Memory management mechanism
• In programming, memory management is a crucial aspect to
ensure the performance and stability of an application. C#
provides an automatic memory management mechanism
called Garbage Collection (GC), which relieves developers
from manually releasing memory as required in lower-level
languages (like C, C++).
• Manages memory, techniques and best practices related to
this topic.

@CMC UNI 2024


3.2. Memory management mechanism
• Garbage Collection
• Stack và Heap
• Finalizers và Dispose Pattern
• Keyword "using“
• Memory Leaks và Best Practices

@CMC UNI 2024


How Garbage Collection (GC) Works
• GC automatically collects objects that are no longer referenced
to free up memory.
• GC divides heap memory into three generations: Gen 0, Gen 1,
and Gen 2.
• Gen 0: Contains newly created objects.
• Gen 1: Contains objects that survived at least one garbage
collection.
• Gen 2: Contains long-lived objects.

@CMC UNI 2024


Garbage Collection Steps
• Marking: GC identifies and marks which objects are still
referenced.
• Relocating: GC moves live objects to consolidate
fragmented memory areas.
• Compacting: GC frees up unused memory by removing
unreferenced objects

@CMC UNI 2024


Stack và Heap
• Stack:
✓The stack is a small, fast memory area used to store local variables and
method calls.
✓Managed by the LIFO (Last In, First Out) principle.
✓Local variables are created on the stack and automatically released
when the method ends.
• Heap:
✓The heap is a larger, slower memory area compared to the stack, used
to store dynamically created objects.
✓Heap memory needs careful management to avoid memory leaks.
✓Objects created using the new keyword are allocated on the heap.
@CMC UNI 2024
Finalizers và Dispose Pattern
• Finalizers:
✓ Finalizer (destructor) is a special method, ~ClassName(),
called before the object is collected by the GC.
✓Overuse of finalizers is discouraged as they can slow down the
garbage collection process.
• Dispose Pattern and IDisposable Interface:
✓IDisposable is an interface providing the Dispose method to
release non-memory resources (e.g., files, network
connections).
✓This pattern ensures timely release of resources and prevents
leaks.
@CMC UNI 2024
Example of IDisposable
public class Resource : IDisposable protected virtual void Dispose(bool disposing)
{ {
private bool disposed = false; if (disposed)
public void UseResource() return;
{
if (disposing)
if (disposed) {
throw new // Giải phóng tài nguyên quản lý
ObjectDisposedException("Resource");
}
// Logic sử dụng tài nguyên // Giải phóng tài nguyên không quản lý
} disposed = true;
public void Dispose() }
{ ~Resource()
Dispose(true); {
Dispose(false);
GC.SuppressFinalize(this);
}
} }

@CMC UNI 2024


Using Statement
• The using keyword ensures that the Dispose method is
called automatically when the object goes out of scope.
• Helps write cleaner and more maintainable code.

@CMC UNI 2024


Example of using statement
class Program
{
static void Main()
{
using (var resource = new Resource())
{
resource.UseResource();
} // resource.Dispose() được gọi tự động
}
}

@CMC UNI 2024


Best Practices
• Avoid Creating Unnecessary Objects: Minimize the
creation of temporary and short-lived objects.
• Proper Use of Dispose: Ensure non-memory resources
are released correctly.
• Use using Statement: Helps manage resources clearly
and automatically.

@CMC UNI 2024


THANK YOU

@CMC UNI 2024 32

You might also like