OCI-C-Unit-4
OCI-C-Unit-4
Unit 4
Exception Handling
What is an exception?
An exception is a problem (error) that arises during the execution of a program.
In C#, an exception is an event or object which is thrown at runtime. All exceptions the
derived from System.Exception class.
It is a runtime error that can be handled. If we don't handle the exception, it prints an
exception message and terminates the program.
Advantage
It maintains the normal flow of the application. In such a case, the rest of the code is
executed even after the exception.
C# exception handling is built upon four keywords: try, catch, finally, and throw.
• try − A try block identifies a block of code for which particular exceptions is
activated. It is followed by one or more catch blocks.
• 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.
www.ourcreativeinfo.in
OCI C# Unit 4
www.ourcreativeinfo.in
OCI C# Unit 4
An exception can be raised manually by using the throw keyword. Any type of exception
which is derived from the Exception class can be raised using the throw keyword.
using System;
namespace throwdemo
{
public class Student
{
public string StudentName { get; set; }
}
class Program
{
static void Main(string[] args)
{
Student std = null;
try
{
PrintStudentName(std);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
public static void PrintStudentName(Student std)
{
if (std == null)
throw new NullReferenceException("Student object is null.");
Console.WriteLine(std.StudentName);
}
}
}
Output:
4
Pre-defined Exception classes
C# .NET includes built-in exception classes for every possible error.
The Exception class is the base class of all the exception classes.
www.ourcreativeinfo.in
OCI C# Unit 4
When an error occurs, either the application code or the default handler
handles the exception.
www.ourcreativeinfo.in
OCI C# Unit 4
Before creating the Custom Exception class, we need to see the class definition
of the Exception class as our Custom Exception class is going to be inherited
from the parent Exception class. If you go to the definition of Exception class,
then you will see the following.
As you can see, the Exception class has some constructors, some virtual and
non-virtual properties, and some virtual and non-virtual methods. The virtual
members you can override in the child of this Exception class and you can
directly consume the non-virtual members using the child class instance.
Now, to create a Custom Exception class in C#, we need to follow the below
steps.
Step1: Define a new class inheriting from the predefined Exception class so that
the new class also acts as an Exception class.
www.ourcreativeinfo.in
OCI C# Unit 4
Step2: Then as per your requirement, override the virtual members that are
defined inside the Exception class like Message, Source, StackTrace, etc with the
required error message.
Let us understand how to create a custom exception in C# with an example.
Create a class file with the name OddNumberException.cs and then copy and
paste the following code into it. Here, you can see that the
OddNumberException class is inherited from the built-in Exception class and
here we are re-implementing two virtual properties i.e. Message and HelpLink.
Now, we can create an instance of OddNumberException class and if we invoke
Message and HelpLink properties, then these two properties are going to be
executed from this class only. But if you invoke the Source and StackTrace
properties, then those properties are going to be executed from the Exception
class only as we have not re-implemented these properties. This is the concept
of Method Overriding in C#.
using System;
namespace ExceptionHandlingDemo
{
//Creating our own Exception Class by inheriting Exception class
public class OddNumberException : Exception
{
//Overriding the Message property
public override string Message
{
get
{
return "Divisor Cannot be Odd Number";
}
}
//Overriding the HelpLink Property
public override string HelpLink
{
get
{
return "Get More Information from here:
https://dotnettutorials.net/lesson/create-custom-
exception-csharp/";
}
}
}
}
Now, as per our business logic, we can explicitly create an instance of the
OddNumberException class and we can explicitly throw that instance from our
application code. For a better understanding, please have a look at the following code.
Here, inside the Main method, we are taking two numbers from the user and then
www.ourcreativeinfo.in
OCI C# Unit 4
7 checking if the second number is odd or not. If the second number i.e. divisor is odd, then
we are creating an instance of the OddNumberException class and throwing that instance.
And in the Catch block, we are handling that exception and we simply printing Message,
StackTrace, Source, and HellpLink properties. Here, if OddNumberException occurred,
then Message and HelpLink properties are going to execute from OddNumberException
class and Source and StackTrace properties are going to be executed from the pre-defined
parent Exception class.
using System;
namespace ExceptionHandlingDemo
{
class Program
{
static void Main(string[] args)
{
int Number1, Number2, Result;
try
{
Console.WriteLine("Enter First Number:");
Number1 = int.Parse(Console.ReadLine());
Console.WriteLine("Enter Second Number:");
Number2 = int.Parse(Console.ReadLine());
if (Number2 % 2 > 0)
{
throw new OddNumberException();
}
Result = Number1 / Number2;
Console.WriteLine(Result);
}
catch (OddNumberException one)
{
Console.WriteLine("Message:” +one.Message);
Console.WriteLine("HelpLink:” +one.HelpLink);
Console.WriteLine("Source:” +one.Source);
Console.WriteLine("StackTrace:” +one.StackTrace);
}
Console.WriteLine("End of the Program");
Console.ReadKey();
}
} }
Output:
www.ourcreativeinfo.in
OCI C# Unit 4
www.ourcreativeinfo.in
OCI C# Unit 4
Once the object is allocated with memory, it is necessary to release that memory so that
it is used for further processing, otherwise, it would result in memory leaks. We have a
class in .Net that releases memory automatically for us when the object is no longer
used. We will try to understand the entire scenario thoroughly of how objects are
created and allocated memory and then deallocated when the object is out of scope.
The class is a blueprint that describes how an instance of this type will look and feel in
memory. This instance is the object of that class type. A block of memory is allocated
when the new keyword is used to instantiate the new object and the constructor is
called. This block of memory is big enough to hold the object. When we declare a class
variable it is allocated on the stack and the time it hits a new keyword and then it is
allocated on the heap. In other words, when an object of a class is created it is allocated
on the heap with the C# new keyword operator. However, a new keyword returns a
reference to the object on the heap, not the actual object itself. This reference variable is
stored on the stack for further use in applications.
When the new operator is used to create an object, memory is taken from the managed
heap for this object and the managed heap is more than just a random chunk of memory
accessed by the CLR. When the object is no longer used then it is de-allocated from the
memory so that this memory can be reused.
The garbage collector cleans up managed resources automatically since the managed
code is directly targeted by the CLR. But when the object uses unmanaged resources like
database connections or file manipulation, that needs to be released manually and this
can be done by a finalized method.
www.ourcreativeinfo.in
OCI C# Unit 4
We use the destructor method using the (~) sign in our code to destroy the objects and
this destructor is converted into a finalize method (check in the compiled code). This is
known as a finalization process. If we are implementing Finalize(), we do not have control
since when this method should be called the garbage collector takes care of this on its
own.
There is another method, Dispose(), that releases managed and unmanaged resources
explicitly. This method is the single method in an IDisposable interface and can be used
to release unmanaged resources manually.
namespace ObjectLifeTime;
class Foo
{
public Foo()
{
// This is the implementation of
// default constructor.
}
public Foo(int x)
{
// This is the implementation of
// the one-argument constructor.
}
~Foo()
{
// This is the implementation of the destructor.
}
public Foo(int x, int y)
{
// This is the implementation of
// the two-argument constructor.
}
public static void Main(string[] args)
{
var defaultfoo = new Foo(); // Call default constructor
var foo = new Foo(14); // Call first constructor
var foo2 = new Foo(12, 16); // Call overloaded constructor
}
}
www.ourcreativeinfo.in
OCI C# Unit 4
System.GC Type
The garbage collector is a common language runtime component that controls the
allocation and release of managed memory. The methods in this class influence when
garbage collection is performed on an object and when resources allocated by an object
are released.
The garbage collector will destroy the object when it is no longer needed.
The base class libraries provide a class type named System.GC allows you to
programmatically interact with the garbage collector using a set of static members.
www.ourcreativeinfo.in
OCI C# Unit 4
using System;
public class Demo
{
public static void Main(string[] args)
{
Console.WriteLine("The number of generations are: " + GC.MaxGeneration);
Console.ReadLine();
}
}
In the above program, the GC.MaxGeneration property is used to find the
maximum number of generations that are supported by the system i.e. 2.
using System;
public class Demo
{
public static void Main(string[] args)
{
Demo obj = new Demo();
Console.WriteLine("The generation number of object obj is: "
+ GC.GetGeneration(obj));
Console.ReadLine();
}
}
Output:
www.ourcreativeinfo.in
OCI C# Unit 4
12
www.ourcreativeinfo.in
OCI C# Unit 4
ET Assemblies
An assembly is the compiled format of any .Net program which may be .dll or .exe.
An Assembly is a basic building block of .Net Framework applications. It is basically a
compiled code that can be executed by the CLR.
An assembly is a collection of types and resources that are built to work together and
form a logical unit of functionality. An Assembly can be a DLL or exe depending upon the
project that we choose.
Assemblies are the fundamental units of deployment, version control, reuse, activation
scoping, and security permissions for .NET-based applications. An assembly is a
collection of types and resources that are built to work together and form a logical unit of
functionality. Assemblies take the form of executable (.exe) or dynamic link library (.dll)
files, and are the building blocks of .NET applications. They provide the common language
runtime with the information it needs to be aware of type implementations.
The .Net Framework keeps executable code or DLL in the form of assembly.
- The .Net Framework maintains multiple versions of the application in the system
through assembly.
- The assemblies have MSIL code and manifest that contains metadata.
• Assemblies are used for the programs themselves as well as any dependent
libraries.
• .NET program can be executed as one or more assemblies, with no other required
artifacts, beyond the appropriate .NET implementation.
• The format is fully specified and standardized as ECMA 335. All .NET compilers
and runtimes use this format.
www.ourcreativeinfo.in
OCI C# Unit 4
14
• The .NET binary format is based on the Windows PE file format. In fact, .NET class
libraries are conformant Windows PEs, and appear on first glance to be Windows
dynamic link libraries (DLLs) or application executables (EXEs).
• The format is fully specified and standardized as ECMA 335. All .NET compilers
and runtimes use this format. The presence of a documented and infrequently
updated binary format has been a major benefit (arguably a requirement) for
interoperability. The format was last updated in a substantive way in 2005 (.NET
Framework 2.0) to accommodate generics and processor architecture.
• The format is CPU- and OS-agnostic. It has been used as part of .NET
implementations that target many chips and CPUs. While the format itself has
Windows heritage, it is implementable on any operating system. Its arguably most
significant choice for OS interoperability is that most values are stored in little-
endian format. It doesn’t have a specific affinity to machine pointer size (for
example, 32-bit, 64-bit).
• The .NET assembly format is also very descriptive about the structure of a given
program or library. It describes the internal components of an assembly,
specifically assembly references and types defined and their internal structure.
Tools or APIs can read and process this information for display or to make
programmatic decisions.
www.ourcreativeinfo.in
OCI C# Unit 4
15
• Example:
Using System;
Namesapce SingleFileAssembly
{
public class Employee
{
public static void main()
{
Console.Writeline(“This is single file assembly”);
Console.ReadLine();
}
}
}
MultiFile Assembly
A multi-file assembly, on the other hand, is a set of . NET modules that are deployed and
versioned as a single unit.
www.ourcreativeinfo.in
OCI C# Unit 4
1. Private Assembly
Private Assemblies are designed to be used by one application and must reside in
that application's directory or subdirectory.
It is an assembly that is being used by a single application only. Suppose we have a
project in which we refer to a DLL so when we build that project that DLL will be
copied to the bin folder of our project. That DLL becomes a private assembly within
our project. Generally, the DLLs that are meant for a specific project are private
assemblies.
2. Shared Assembly
Assemblies that can be used in more than one project are known to be shared
assemblies. Shared assemblies are generally installed in the GAC. Assemblies that are
installed in the GAC are made available to all the .Net applications on that machine.
www.ourcreativeinfo.in
OCI C# Unit 4
Thank You
(Our Creative Info)
www.ourcreativeinfo.in