To handle exceptions, take the following steps:
-
Execute any code that you suspect might throw an exception (such as code that opens a file or allocates memory) within a try block.
-
Catch any exceptions that are thrown in a catch block.
A try block is created using the keyword try and is enclosed in braces. A catch block is created using the keyword catch and is also enclosed in braces.
Example : Try and catch blocks
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...");
Console.WriteLine("Exit Run...");
}
public void Func1()
{
Console.WriteLine("Enter Func1...");
Func2();
Console.WriteLine("Exit Func1...");
}
public void Func2()
{
Console.WriteLine("Enter Func2...");
try
{
Console.WriteLine("Entering try block...");
throw new System.Exception();
Console.WriteLine("Exiting try block...");
}
catch
{
Console.WriteLine("Exception caught and handled!");
}
Console.WriteLine("Exit Func2...");
}
}
}
Output:
Enter Main...
Enter Run...
Enter Func1...
Enter Func2...
Entering try block...
Exception caught and handled!
Exit Func2...
Exit Func1...
Exit Run...
Exit Main...
Following the try statement is the catch statement. In a real catch statement, you might silently fix the problem (e.g., retry a database connection), or you might interact with the user to solve the problem (e.g., offer the user the opportunity to close other applications and free up memory).
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