Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

Unit-4 (C#.NET)

Uploaded by

ramya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Unit-4 (C#.NET)

Uploaded by

ramya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

C# .

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

III-YEAR-I-SEMESTER 2019-20 CSE Page 1 of 15


C# .NET UNIT - 4

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;
Console.WriteLine("{0}",a)
}
}
}
Output:
Error 1 ; expected D:\Dot Net\Programs\w\w\Program.cs 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

III-YEAR-I-SEMESTER 2019-20 CSE Page 2 of 15


C# .NET UNIT - 4

Example 2:
int[ ] a=new int[3] {1,2,3};
Console.WriteLine(“{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;
Console.WriteLine("Enter a number\t:");
a= int.Parse(Console.ReadLine());
Console.WriteLine("{0}", a);
}
}
}
Output:
Enter a number :
Welcome

III-YEAR-I-SEMESTER 2019-20 CSE Page 3 of 15


C# .NET UNIT - 4

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
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


xceptions:
Def: An exception is an unwanted or unexpected event, which occurs
during the execution
on of a program i.e at runtime that disrupts the normal
flow of the program’s instructions. Sometimes during the 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 indication regarding
something wrong within the code. Exceptions are of two types:
a) Pre-defined
defined exceptions.
b) User-defined
defined Exceptio
Exceptions.
In the table 4.1 types of predefined exceptions are displayed with
descriptions.

III-YEAR-I-SEMESTER 2019-20 CSE Page 4 of 15


C# .NET UNIT - 4

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.

III-YEAR-I-SEMESTER 2019-20 CSE Page 5 of 15


C# .NET UNIT - 4

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
{
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 . . .

III-YEAR-I-SEMESTER 2019-20 CSE Page 6 of 15


C# .NET UNIT - 4

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

III-YEAR-I-SEMESTER 2019-20 CSE Page 7 of 15


C# .NET UNIT - 4

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)
{

Console.WriteLine("Not possible to Divide by zero");


}
catch (IndexOutOfRangeException)
{
Console.WriteLine("Index is Out of Range");
}
}
}
}
Output:
Number: 8
Divisor: 2
Quotient: 4
Number: 17

III-YEAR-I-SEMESTER 2019-20 CSE Page 8 of 15


C# .NET UNIT - 4

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");
}

III-YEAR-I-SEMESTER 2019-20 CSE Page 9 of 15


C# .NET UNIT - 4

}
}
}
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"));
}

III-YEAR-I-SEMESTER 2019-20 CSE Page 10 of 15


C# .NET UNIT - 4

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

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 “System.Exception” class.
Some of the exception classes derived from the “System.Exception” class
are the System.ApplicationException and System.SystemException classes.

The “System.ApplicationException” class supports exceptions


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

The “System.SystemException” class is the base class for all


predefined system exception.

Example program for usage of exception class:


using System;
namespace UserdefinedException
{
class MyException : Exception

III-YEAR-I-SEMESTER 2019-20 CSE Page 11 of 15


C# .NET UNIT - 4

{
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 . . .

III-YEAR-I-SEMESTER 2019-20 CSE Page 12 of 15


C# .NET UNIT - 4

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

III-YEAR-I-SEMESTER 2019-20 CSE Page 13 of 15


C# .NET UNIT - 4

4. Which of this will be executed even if no exceptions are found? [ ]


(a) throws
(b) finally
(c) throw
(d) catch

5. Which of these keywords are used for generating an exception


manually? [ ]
(a) try
(b) catch
(c) throw
(d) check
6. Which of these keywords are used for the block to handle the
exceptions generated by try block? [ ]
(a) Try
(b) Catch
(c) Throw
(d) check
7. What will be the output of the given code snippet? [ ]
class program
{
public static void Main(string[] args)
{
try
{
int a = args.Length;
int b = 1 / a;
Console.WriteLine(a);
}
catch (ArithmeticException e)
{
Console.WriteLine("1");
}
Console.ReadLine();
}
}
(a) 0
(b) 1
(c) Compile Time Error
(d) Run Time Error

III-YEAR-I-SEMESTER 2019-20 CSE Page 14 of 15


C# .NET UNIT - 4

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?

III-YEAR-I-SEMESTER 2019-20 CSE Page 15 of 15

You might also like