Try and catch

The try and catch keywords are the two most important keywords for exception handling in C#. If you write a try block without a catch block, then it won't make any sense because, if a try block throws an exception and there is no catch block to handle it, then what is the benefit? The exception will still be unhandled. The catch block actually depends on a try block. A catch block can't exist if there is no try block associated with it. Let's look at how we can write a try-catch block:

try 
{
int a = 5 / 0;
}
catch(DivideByZeroException ex)
{
Console.WriteLine(“You have divided by zero”);
}

We can also have more catch blocks for a try block. Let's look at an example of this:

try 
{
int a = 5 / 0;
}
catch(DivideByZeroException ex)
{
Console.WriteLine(“You have divided by zero”);
}
catch(Exception ex)
{
Console.WriteLine(“Normal exception”);
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.126.211