0% found this document useful (0 votes)
8 views8 pages

Unit_4

The document covers errors and exception handling in C# programming, detailing debugging processes, types of errors (syntax, runtime, and logical), and exception handling mechanisms using try, catch, finally, and throw keywords. It explains exception hierarchy, nested try-catch structures, and user-defined exceptions, providing code examples for clarity. The content emphasizes the importance of handling exceptions to maintain program stability and prevent crashes.

Uploaded by

bhatt navtej
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)
8 views8 pages

Unit_4

The document covers errors and exception handling in C# programming, detailing debugging processes, types of errors (syntax, runtime, and logical), and exception handling mechanisms using try, catch, finally, and throw keywords. It explains exception hierarchy, nested try-catch structures, and user-defined exceptions, providing code examples for clarity. The content emphasizes the importance of handling exceptions to maintain program stability and prevent crashes.

Uploaded by

bhatt navtej
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/ 8

10/26/2020

Errors and Exception Handling


Unit 4

Errors and Exception Handling

 Debugging,
 Types of Errors,
 Exceptions,
 Syntax of Exception handling code,
 Multiple Catch statements,
 Exception hierarchy,
 Using Finally statement,
 Nested Try blocks,
 Throwing our own Exceptions,
 Checked and Unchecked Operators,
 Using Exceptions for debugging

1
10/26/2020

Debugging
 Debugging is the process of detecting and removing of
existing and potential errors (also called as 'bugs') in a
software code that can cause it to behave unexpectedly
or crash.
 To prevent incorrect operation of a software or system,
debugging is used to find and resolve bugs or defects.

Types of Errors
 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-
1. Syntax Errors
 Syntax errors occur during development, when you make type mistake in code. For example,
instead of writing while, you write WHILE then it will be a syntax error since C# is a case
sensitive language.

1. 2. Runtime Errors (Exceptions)


 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.
 int a = 5, b = 0;
 int result = a / b; // DivideByZeroException
 Exceptions can be handled by using try-catch blocks.
 3. 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
 1. int a = 5, b = 6;
 2. double avg = a + b / 2.0; // logical error, it should be (a + b) / 2.0

2
10/26/2020

Exceptions
 Exceptions provide a way to transfer control from one part of a program to
another. 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.
 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.

try/catch
 In C# programming, exception handling is performed by try/catch statement. The try block in
C# is used to place the code that may throw exception. The catch block is used to handle the
exception. The catch block must be preceded by try block.

 C# example without try/catch


 using System;
 public class ExExample
 {
 public static void Main(string[] args)
 {
 int a = 10;
 int b = 0;
 int x = a/b;
 Console.WriteLine("Rest of the code");
 }
 }
 Output:
 Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero.

3
10/26/2020

try/catch example
 using System;
 public class ExExample
 {
 public static void Main(string[] args)
 {
 try
 {
 int a = 10;
 int b = 0;
 int x = a / b;
 }
 catch (Exception e) { Console.WriteLine(e); }

 Console.WriteLine("Rest of the code");


 }
 }
 Output:

 System.DivideByZeroException: Attempted to divide by zero.


 Rest of the code

finally
 C# finally block is used to execute important code which is to be executed whether exception is handled or not.
 It must be preceded by catch or try block.
 C# finally example if exception is handled
 using System;
 public class ExExample
 {
 public static void Main(string[] args)
 {
 try
 {
 int a = 10;
 int b = 0;
 int x = a / b;
 }
 catch (Exception e) { Console.WriteLine(e); }
 finally { Console.WriteLine("Finally block is executed"); }
 Console.WriteLine("Rest of the code");
 }
 }
 Output:
 System.DivideByZeroException: Attempted to divide by zero.
 Finally block is executed
 Rest of the code

4
10/26/2020

Multiple Catch statements


class Program
{
static void Main(string[] args)
{
int a, b, c;
Console.WriteLine("ENTER ANY TWO NUBERS");
try
{
a = int.Parse(Console.ReadLine());
b = int.Parse(Console.ReadLine());
c = a / b;
Console.WriteLine("C VALUE = " + c);
}
catch (DivideByZeroException d)
{
Console.WriteLine("second number should not be zero");
}
catch (FormatException f)
{
Console.WriteLine("enter only integer numbers");
}
Console.ReadKey();
}
}

Exception Hierarchy

 In C#, all the exceptions are derived from the base class Exception.
 Exception gets further divided into two branches as ApplicationException and
SystemException.
 SystemException is a base class for all CLR or program code generated errors.
 ApplicationException is a base class for all application related exceptions.
 All the exception classes are directly or indirectly derived from the Exception
class.
 In case of ApplicationException, the user may create its own exception types
and classes.
 But SystemException contains all the known exception types such as
DivideByZeroException or NullReferenceException etc.

5
10/26/2020

Nested try-catch

 C# allows nested try-catch blocks.


 When using nested try-catch blocks, an exception will be caught in the first
matching catch block that follows the try block where an exception occurred.

Example: Nested try-catch


static void Main(string[] args)
{
var divider = 0;
try
{
try
{
var result = 100/divider;
}
catch
{
Console.WriteLine("Inner catch");
}
}
catch
{
Console.WriteLine("Outer catch");
}
}
Output: Inner catch
An inner catch block will be executed in the above example because it is the first
catch block that handles all exception types.
If there isn't an inner catch block that matches with raised exception type, then the
control will flow to the outer catch block until it finds an appropriate exception filter.

6
10/26/2020

Example: Nested try-catch


static void Main(string[] args)
{
var divider = 0;
try
{
try
{
var result = 100/divider;
}
catch(NullReferenceException ex)
{
Console.WriteLine("Inner catch");
}
}
catch
{
Console.WriteLine("Outer catch");
}
}
Output:
Outer catch
In the above example, an exception of type DivideByZeroException will be raised. Because an
inner catch block handles only the NullReferenceTypeException, it will be handle by an outer
catch block.

User-Defined Exceptions
 User-defined exceptions are useful when we want to code an
exception that may not be defined by the language.
 For example, in a boiler room, if the temperature rises above some
threshold then the heat must be turned off.
 For understanding how user-defined exceptions are used we take an
example of a division by zero.
 Here we define a class DivByZero that inherits from Exception and is
called by the DivisionOperation function when the denominator is
equal to zero.
 Since the call for the function is may or may not throw an exception it
is placed in the try block.
 A catch block is defined to catch any exception of type Exception and
the Message property prints the type of exception that has occurred.

7
10/26/2020

User-Defined Exceptions
// C# program to show the user defined exceptions // Main
using System;
static void Main(string[] args)
// User defined Exception class {
// Child of Exception Program obj = new Program();
class DivByZero : Exception {
double num = 9, den = 0, quotient;
// Constructor try {
public DivByZero() // Code block that may cause an exception
{
Console.Write("Exception has occurred : "); quotient = obj.DivisionOperation(num, den);
} Console.WriteLine("Quotient = {0}", quotient);
} }
class Program { // Catch block to catch the generic exception
catch (Exception e) {
// Method to perform Division // Message property of exception object e
public double DivisionOperation(double numerator,
double denominator) // will give the specific type of the exception
{ Console.Write(e.Message);
// throw exception when denominator }
// value is 0
if (denominator == 0) }
throw new DivByZero(); }
Output:
// Otherwise return the result of the division
return numerator / denominator; Exception has occurred : Exception of type 'DivByZero' was
} thrown.

You might also like