Unit-4 (C#.NET)
Unit-4 (C#.NET)
NET UNIT - 4
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;
Console.WriteLine(“{0}”,a) //syntax error, semicolon is missing
Name of
the project
Error
Description
Example 2:
int[ ] a=new int[3] {1,2,3};
Console.WriteLine(“{0}”,a[4]); // ArrayIndexOutOfRange Exception
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
wrong.
Example:
int a = 5, b = 6;
double avg = a + b / 2.0; // logical error, it should be (a + b) / 2.0
Example program1:
using System;
namespace Sample
{
class Program
{
static void Main(string[] args)
{
int n;
try
{
Console.WriteLine("Enter a number\t:");
n = int.Parse(Console.ReadLine());
Console.WriteLine("You have entered :" + n);
}
catch (Exception e)
{
Console.WriteLine("Exception " + e.ToString());
}
}
}
}
Output:
Enter a number :
Hai
Exception System.FormatException: Input string was not in a correct
format.
at System.Number.StringToNumber(String str, NumberStyles options,
NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
at System.Number.ParseInt32(String s, NumberStyles style,
NumberFormatInfo info)
at Sample.Program.Main(String[] args) in D:\Dot
Net\Programs\w\w\Program.cs: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
{
Console.WriteLine("Enter the first number");
a = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the second number");
b = int.Parse(Console.ReadLine());
x = (a + b) / (a - b);
Console.WriteLine("The answer is {0}", x.ToString());
}
catch (ArithmeticException e)
{
Console.WriteLine("Arithmetic Exception caught");
}
finally
{
Console.WriteLine("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 < number.Length; j++)
try
{
Console.WriteLine("Number: " + number[j]);
Console.WriteLine("Divisor: " + divisor[j]);
Console.WriteLine("Quotient: " + number[j] / divisor[j]);
}
catch (DivideByZeroException)
{
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);
Console.WriteLine("Result :{0}",result);
}
catch(Exception e)
{
Console.WriteLine("Caught inside function");
}
}
static void Main(string[] args)
{
int x, y;
try
{
Console.WriteLine("Enter the first number:");
x = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the second number:");
y = int.Parse(Console.ReadLine());
func(x, y);
}
catch (Exception e)
{
Console.WriteLine("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
{
Console.WriteLine("Temperature: {0}", temperature);
}
}
}
public class Program
{
public static void Main(string[] args)
{
Temperature temp = new Temperature();
try
{
temp.showTemp();
}
catch(TempIsZeroException e)
{
Console.WriteLine("TempIsZeroException: {0}", e.Message);
}
}
}
}
Output:
TempIsZeroException: Zero Temperature found
{
public MyException(string str)
{
Console.WriteLine("User defined exception");
}
}
class Program
{
static void Main(string[] args)
{
try
{
throw new MyException("NewWorld");
}
catch (Exception e)
{
Console.WriteLine("Exception caught here" + e.ToString());
}
finally
{
Console.WriteLine("LAST STATEMENT");
}
}
}
}
Output:
User defined exception
Exception caught hereUserdefinedException.MyException: Exception of type
'UserdefinedException.MyException' was thrown.
at UserdefinedException.Program.Main(String[] args) in D:\Dot
Net\Programs\UserdefinedException\UserdefinedException\Program.cs:line
21
LAST STATEMENT
Press any key to continue . . .
Assignment-Cum-Tutorial Questions
Section-A
Objective Questions
1. class Sample {
public static void main(String args[]) {
int x = 0;
int y = 10;
int z = y/x;
}
} [ ]
(a) Compile time error
(b) Compiles and runs fine
(c) throws an arithmetic exception
(d) None of the above
2. Which among the following is NOT an exception? [ ]
a) Stack Overflow
b) Arithmetic Overflow or underflow
c) Incorrect Arithmetic Expression
d) All of the mentioned
3. What will be the output of the following C# code? [ ]
class Output
{
public static void main(String args[])
{
try
{
int a = 9;
int b = 5;
int c = a / b - 5;
Console.WriteLine("Hello");
}
catch(Exception e)
{
Console.WriteLine("C");
}
finally
{
Console.WriteLine("sharp");
}
}
}
a) Hello
b) C
c) Hellosharp
d) Csharp
Section-B
Subjective Questions
1. What is an error?
2. List and explain different types of errors in C#?
3. What is an exception?
4. List and explain different types of exceptions in C#?
5. Explain exception handling mechanism in C#?
6. Explain the difference between error and exception in C#?
7. What is the main use of a finally block in exception handling?
8. What is user exception and how to raise it in C#?
9. What is the base class from which all the exceptions are derived?
10. Does finally get executed if the code throws an error?