0% found this document useful (0 votes)
28 views12 pages

C# Error and Exception Handling Guide

This document discusses errors and exceptions in programming, categorizing them into syntax errors, runtime errors, and logical errors, along with their definitions and examples. It also explains exception handling mechanisms in C#, including try-catch blocks, multi-catch statements, nested try-catch blocks, and user-defined exceptions. Additionally, it outlines the usage of the Exception class and provides example programs to illustrate these concepts.
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)
28 views12 pages

C# Error and Exception Handling Guide

This document discusses errors and exceptions in programming, categorizing them into syntax errors, runtime errors, and logical errors, along with their definitions and examples. It also explains exception handling mechanisms in C#, including try-catch blocks, multi-catch statements, nested try-catch blocks, and user-defined exceptions. Additionally, it outlines the usage of the Exception class and provides example programs to illustrate these concepts.
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

UNIT – 4

Error and Exceptions


4.1 Types of Errors and Exceptions:
4.1.1 Types of errors:
Def: Errors refer to the mistake or faults which occur during program
development or execution. If you don't find them and correct them, they
cause a program to produce wrong results.
In programming language errors can be divided into three categories
as given below-
a) Syntax Errors or compile time errors.
b) Runtime Errors.
c) Logical Errors.
a) Syntax Errors or compile time errors:
Syntax Errors, also known as Compilation errors are the most
common type of errors. Most Syntax errors are caused by mistakes that you
make when writing code. If you are using the coding environment like Visual
Studio, it is able to detect them as soon as you write them; also you can fix
them easily as soon as they occur. When you compile your application in the
development environment, the compiler would point out where the problem
is so you can fix it instantly. In visual studio errors are shown in error pane.
The following gives some reasons for such errors:
1. Missing semicolon.
2. Misspelt keywords.
3. Not having a matching closing brace for each opening brace.
4. Use of undeclared or uninitialized variables.
5. Incompatible assignments.
6. Inappropriate references.
Example 1: When you forgot to type a semicolon (;) after the statement, the
compiler shows the syntax error and it would point out where the problem
occurred.
int a=10;
[Link](“{0}”,a) //syntax error, semicolon is missing
Example 2: Instead of writing while, you write WHILE then it will be a
syntax error since C# is a case sensitive language.
bool flag=true;
WHILE (flag) //syntax error, since c# is case sensitive
{
//code
}
Example program:
using System;
namespace Sample
{
class Program
{
static void Main(string[] args)
{
int a = 10;
[Link]("{0}",a)
}
}
}
Output:
Error 1 ; expected D:\Dot Net\Programs\w\w\[Link] 13 39
Sample

Name of
the project
Error
Description

Line number and column number

Figure 4.1: Error shown in an error pane


b) Runtime Errors:
Runtime errors occur during execution of the program. These are also
called exceptions. This can be caused due to improper user inputs, improper
design logic or system errors. Runtime errors are also known as exceptions.
Exceptions can be handled by using try-catch blocks.
Example 1:
int a = 5, b = 0;
int result = a / b; // DivideByZeroException
Example 2:
int[ ] a=new int[3] {1,2,3};
[Link](“{0}”,a[4]); // ArrayIndexOutOfRange Exception

Figure 4.2: ArrayIndexOutOfBound Exception


Example program for runtime exception:
using System;
namespace Sample
{
class Program
{
static void Main(string[] args)
{
int a;
[Link]("Enter a number\t:");
a= [Link]([Link]());
[Link]("{0}", a);
}
}
}
Output:
Enter a number :
Welcome
Figure 4.2: Exception encountered on entering an illegal value

c) Logical Errors:
Logic errors occur when the program is written fine but it does not
produce desired result. Logic errors are difficult to find because you need to
know for sure that the result is wrong.
Example:
int a = 5, b = 6;
double avg = a + b / 2.0; // logical error, it should be (a + b) / 2.0

4.1.1 Types of exceptions:


Def: An exception is an unwanted or unexpected event, which occurs
during the execution of a program i.e at runtime that disr upts the normal
flow of the program’s instructions. Sometimes during t he execution of
program, the user may face the possibility that the program may crash or
show an unexpected event during its runtime execution. This unwanted
event is known as Exception and is generally gives the indi cation regarding
something wrong within the code. Exceptions are of two types:
a) Pre-defined exceptions.
b) User-define d Exceptions.
In the table 4.1 types of predefined exceptions are displayed with
descriptions.
Table 4.1: Types of Exceptions
Exception Class Description
Exception For general exception.
Overflow or underflow due to an Arithmetic
Arithmetic Exception
Exception.
When the denominator of an Arithmetic
DivideByZeroExceptions
Exception becomes zero.
NotFiniteNumberException Invalid Number.
The operation is not allowed between the
InvalidOperationException
operands.
SystemException Failed runtime check.
CoreException Base class of exception thrown at runtime.
Trying to utilize an exception that has not
NullReferenceException
been dispensed.
StackOverflowException When stack overflows.
Memory allotted to the program not
OutofMemoryException
sufficient.
Missingmemberexception Inappropriate dll accessed.
InvalidcastException Illegal cast attempted.
AccessException Failure to access a type.
Argument Exception Argument invalid.
ArgumentOutofRangeException Argument out of range.
Null argument passed to a method that
Argument Null Exception
does not accept it.
The element that one is trying to input is
ArrayTypeMismatchexception
not of the type of the array in question.
Format Exception Illegal format of the argument.
Trying to access an element from an index
IndexOutofRangeException exceeding the maximum capacity of the
array defined at the runtime.

4.2 Exception handling mechanism – Try, catch, throws and


finally:
In order to handle exceptions, we must first identify the portion of the
code where an exception might occur. After identifying the portion, we must
place that portion in a “try” block. For every “try” block, there has to be a
corresponding “catch” block. Inside the catch block, any of the arguments
shown in Table 4.1 may appear.
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.

Example program1:
using System;
namespace Sample
{
class Program
{
static void Main(string[] args)
{
int n;
try
{
[Link]("Enter a number\t:");
n = [Link]([Link]());
[Link]("You have entered :" + n);
}
catch (Exception e)
{
[Link]("Exception " + [Link]());
}
}
}
}
Output:
Enter a number :
Hai
Exception [Link]: Input string was not in a correct
format.
at [Link](String str, NumberStyles options,
NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
at [Link].ParseInt32(String s, NumberStyles style,
NumberFormatInfo info)
at [Link](String[] args) in D:\Dot
Net\Programs\w\w\[Link]:line 16
Press any key to continue . . .
Example program2:
using System;
namespace ArthimeticException
{
class Program
{
static void Main(string[] args)
{
int a, b, x;
try
{
[Link]("Enter the first number");
a = [Link]([Link]());
[Link]("Enter the second number");
b = [Link]([Link]());
x = (a + b) / (a - b);
[Link]("The answer is {0}", [Link]());
}
catch (ArithmeticException e)
{
[Link]("Arithmetic Exception caught");
}
finally
{
[Link]("This is final block");
}
}
}
}
Output:
Enter the first number
3
Enter the second number
3
Arithmetic Exception caught
This is final block
Press any key to continue . . .
4.3 Multi-catch statement in C#:
The main purpose of the catch block is to handle the exception raised
in the try block. This block is only going to execute when the exception
raised in the program.
In C#, you can use more than one catch block with the try block.
Generally, multiple catch block is used to handle different types of
exceptions means each catch block is used to handle different type of
exception. If you use multiple catch blocks for the same type of exception,
then it will give you a compile-time error because C# does not allow you to
use multiple catch block for the same type of exception. A catch block is
always preceded by the try block.
In general, the catch block is checked within the order in which they
have occurred in the program. If the given type of exception is matched with
the first catch block, then first catch block executes and the remaining of
the catch blocks are ignored. And if the starting catch block is not suitable
for the exception type, then compiler search for the next catch block.
Example program for multi-catch statements:
using System;
namespace Multi
{
public class Program
{
public static void Main(string[] args)
{
int[] number = { 8, 17, 24, 5, 25 };
int[] divisor = { 2, 0, 0, 5 };
for (int j = 0; j < [Link]; j++)
try
{
[Link]("Number: " + number[j]);
[Link]("Divisor: " + divisor[j]);
[Link]("Quotient: " + number[j] / divisor[j]);
}
catch (DivideByZeroException)
{

[Link]("Not possible to Divide by zero");


}
catch (IndexOutOfRangeException)
{
[Link]("Index is Out of Range");
}
}
}
}
Output:
Number: 8
Divisor: 2
Quotient: 4
Number: 17
Divisor: 0
Not possible to Divide by zero
Number: 24
Divisor: 0
Not possible to Divide by zero
Number: 5
Divisor: 5
Quotient: 1
Number: 25
Index is Out of Range
Nested try-catch blocks:
Having a try-catch block within another try-catch block is known as nested
try-catch.
Example program for nested try-catch blocks:
using System;
namespace Nestedtrycatch
{
class Program
{
static void func(int a,int b)
{
double result;
try
{
result=(a+b)/(a-b);
[Link]("Result :{0}",result);
}
catch(Exception e)
{
[Link]("Caught inside function");
}
}
static void Main(string[] args)
{
int x, y;
try
{
[Link]("Enter the first number:");
x = [Link]([Link]());
[Link]("Enter the second number:");
y = [Link]([Link]());
func(x, y);
}
catch (Exception e)
{
[Link]("Caught inside main");
}
}
}
}
Output:
(a) Enter the first number:
3
Enter the second number:
3
Caught inside function
Press any key to continue . . .
(b) Enter the first number:
1
Enter the second number:
Hai
Caught inside main
Press any key to continue . . .
(c) Enter the first number:
5
Enter the second number:
4
Result :9
Press any key to continue . . .
4.4 Creating user defined exceptions:
You can also define your own exception. User-defined exception classes are
derived from the Exception class.
Example Program:
using System;
namespace User
{
public class TempIsZeroException: Exception
{
public TempIsZeroException(string message): base(message)
{
}
}
public class Temperature
{
int temperature = 0;
public void showTemp()
{
if(temperature == 0)
{
throw (new TempIsZeroException("Zero Temperature found"));
}
else
{
[Link]("Temperature: {0}", temperature);
}
}
}
public class Program
{
public static void Main(string[] args)
{
Temperature temp = new Temperature();
try
{
[Link]();
}
catch(TempIsZeroException e)
{
[Link]("TempIsZeroException: {0}", [Link]);
}
}
}
}
Output:
TempIsZeroException: Zero Temperature found

4.5 Usage of Exception class:

C# exceptions are represented by classes. The exception classes in C#


are mainly directly or indirectly derived from the “[Link]” class.
Some of the exception classes derived from the “[Link]” class
are the [Link] and [Link] classes.

The “[Link]” class supports exceptions


generated by application programs. Hence the exceptions defined by the
programmers should derive from this class.

The “[Link]” class is the base class for all


predefined system exception.

Example program for usage of exception class:


using System;
namespace UserdefinedException
{
class MyException : Exception
{
public MyException(string str)
{
[Link]("User defined exception");
}
}
class Program
{
static void Main(string[] args)
{
try
{
throw new MyException("NewWorld");
}
catch (Exception e)
{
[Link]("Exception caught here" + [Link]());
}
finally
{
[Link]("LAST STATEMENT");
}
}
}
}
Output:
User defined exception
Exception caught [Link]: Exception of type
'[Link]' was thrown.
at [Link](String[] args) in D:\Dot
Net\Programs\UserdefinedException\UserdefinedException\[Link]:line
21
LAST STATEMENT
Press any key to continue . . .

You might also like