C # typical examples of error and Exception Handling

Source: Internet
Author: User

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 () ;}}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.