Try Catch Finally in c#

try-catch-finally
In this Section you will learn:

  • What is try catch block in c#?
  • What is finally block in c#?
  • Try catch programming example

Try Catch Finally

Try Catch Finally is the basic building block of exception handling in c#. ‘Try’ block keeps the code which may raise exception at runtime. The ‘catch’ block handle the exception if try block gets error and ‘finally’ block executes always whether exception is raised or not. A try block may have multiple catch blocks.

Programming Example of Try Catch Finally Block

Output Explain

Output 1

First input : 5
Second input : 2

It will not raise any exception and shows output. finally block executed at the end.

Divide Program. You Enter 2 number and we return result
Enter 1st Number:
5
Enter 2nd Number:
2
Divide : 2.5Finally Block: For Continue Press Enter and for Exit press Ctrl + c__

 

Output 2

First input : 5
Second input : 0

It will raise DivideByZeroException and handled by DivideByZeroException catch block.

Divide Program. You Enter 2 number and we return result
Enter 1st Number:
5
Enter 2nd Number:
0
You have Entered 0
More Details about Error:System.DivideByZeroException: Attempted to divide by zero. at System.Decimal.FCallDivide(Decimal& d1, Decimal& d2) at System.Decimal.op_Division(Decimal d1, Decimal d2) at Exception_Handling.Program.Main(String[] args) in c:\Users\Prashant\Docume nts\Visual Studio 2012\Projects\advancecsharp\Exception Handling\Exception Handl ing\Program.cs:line 26Finally Block: For Continue Press Enter and for Exit press Ctrl + c

__

 

Output 3

First input : 4
Second input : k

We have entered second input as alphabet and we all know that a number can’t be divided by alphabet so It will raise FormatException and handled by FormatException catch block.

Divide Program. You Enter 2 number and we return result
Enter 1st Number:
4
Enter 2nd Number:
k
Invalid Input
More Details about Error:System.FormatException: Input string was not in a correct format. at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffe r& number, NumberFormatInfo info, Boolean parseDecimal) at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo in fo) at System.Convert.ToInt32(String value) at Exception_Handling.Program.Main(String[] args) in c:\Users\Prashant\Docume nts\Visual Studio 2012\Projects\advancecsharp\Exception Handling\Exception Handl ing\Program.cs:line 24Finally Block: For Continue Press Enter and for Exit press Ctrl + c

__

 

Summary

In this chapter you have learned try catch and finally block in a brief. It is necessary to learn exception handling for all who want to be a good c# programmer. In the next chapter we will learn how to create your own exception or user defined exception.



Leave a Reply

Your email address will not be published. Required fields are marked *