Check whether the user entered a number in the middle of 0-5: Multiple catch Blocks
Using System; Using System. Collections. Generic; Using System. LINQ; Using System. text; Namespace Predictiondemo { Class Program { Static Void Main ( String [] ARGs ){ String Userinput; While ( True ){Try {Console. Write ( "Input a number between 0 and 5" + "(Or just hit return to exist)>" ); Userinput = console. Readline (); If (Userinput = "" ) Break ; Int Index = convert. toint32 (userinput ); If (Index <0 | index> 5) Throw New Indexoutofrangeexception ( "You typed in" + Userinput); console. writeline ( "Your number was" + Index );} Catch (Indexoutofrangeexception ex) {console. writeline ( "Exception :" + "Number shoshould between 0 and 5 ." + Ex. Message );} Catch (Exception ex) {console. writeline ( "An exception was thrown. message was: {0 }" + Ex. Message );} Catch {Console. writeline ( "Some other exception has occured" );} Finally {Console. writeline ( "Thank you" );}}}}}
When the input value is a number between 0 and 5, the first exception is thrown. If the input value is a string, the second exception is thrown. The third exception does not contain parameters. This Catch Block handles other exceptions that are not programmed by C #.Code.
The following is a try... Finally Exception Handling
static void codewithcleanup () {system. io. filestream file = null ; system. io. fileinfo = null ; try {fileinfo = New system. io. fileinfo ( "C: \ file.txt" ); file = fileinfo. openwrite (); file. WRI Tebyte (0xf);} catch (system. exception e) {system. console. writeline (E. message) ;}< SPAN class = "kwrd"> finally {< SPAN class = "kwrd"> If (file! = null ) {file. Close () ;}}