Throw Statement in C Sharp

To signal an abnormal condition in a C# program, throw an exception by using the throw keyword. The following line of code creates a new instance of System.Exception and then throws it:

throw new System.Exception();

The following example illustrates what happens if you throw an exception and there is no try/catch block to catch and handle the exception. In this example, you'll throw an exception even though nothing has actually gone wrong, just to illustrate how an exception can bring your program to a halt.

Example : Unhandled exception
using System;

namespace ExceptionHandling

{

class Tester

{



static void Main()

{

Console.WriteLine("Enter Main...");

Tester t = new Tester();

t.Run();

Console.WriteLine("Exit Main...");

}

public void Run()

{

Console.WriteLine("Enter Run...");

Func1();
Console.WriteLine("Exit Run...");       

}

public void Func1()

{

Console.WriteLine("Enter Func1...");

Func2();

Console.WriteLine("Exit Func1...");

}


public void Func2()

{

Console.WriteLine("Enter Func2...");

throw new System.Exception();

Console.WriteLine("Exit Func2...");

}

}

}

Output:

Enter Main...

Enter Run...

Enter Func1...

Enter Func2...



Unhandled Exception: System.Exception: Exception of type System.Exception was thrown. at

ExceptionHandling.Tester.Func2() in source\exceptions\exceptionhandling\class1.cs:line 34

at ExceptionHandling.Tester.Func1() in source\exceptions\exceptionhandling\class1.cs:

line 27

at ExceptionHandling.Tester.Run() in source\exceptions\exceptionhandling\class1.cs:

line 19

at ExceptionHandling.Tester.Main() in source\exceptions\exceptionhandling\class1.cs:

line 13

This simple example writes to the console as it enters and exits each method. Main() calls Run(), which in turn calls Func1(). After printing out the Enter Func1 message, Func1() immediately calls Func2(). Func2() prints out the first message and throws an object of type System.Exception.

Execution immediately stops, and the CLR looks to see if there is a handler in Func2(). There is not, and so the runtime unwinds the stack (never printing the exit statement) to Func1(). Again, there is no handler, and the runtime unwinds the stack back to Main(). With no exception handler there, the default handler is called, which prints the error message, and terminates the program.

RELATED POST

VISUAL STUDIO INTRODUCTION

C SHARP INTRODUCTION

C SHARP OUT LOOK

DOT NET AND C SHARP

C SHARP APPLICATION STRICTURE

OOPS INTRODUCTION

OOPS AND C SHARP

IDE AND C SHARP

INSTANTIATING OBJECTS IN C SHARP

CLASSES AND OBJECTS IN C SHARP

OPERATORS IN C SHARP

SWITCH AND ITERATION IN C SHARP

BRANCHING IN C SHARP

CONSTANTS AND STRING

No comments:

Post a Comment