Handling errors in C # often uses these keywords. This article describes its usage
The three keyword try is necessary, otherwise it loses its meaning. Then catch and finally can be used but be careful to follow the principle
One or more catch times can be used without a finally but also.
If the time without catch must be used finally.
Each of these keywords corresponds to a block of code that has its own
Such a form as this
Try { //code } catch { // code } finally { //code }
Now it's time to start talking.
The try code block mainly includes the code for the error such as
i = Convert.ToInt32 (str);
I don't know if I can succeed in the conversion.
Catch is the code that handles exceptions
Finally is the thing to do after handling the exception
Static voidMain (string[] args) { intI=1 ; stringstr ="Dfdfs"; Try{i= Convert.ToInt32 (str);//where there are anomalies. } Catch //(Exception e) { //Console.WriteLine (e.message); i =3;//Handling Exceptions//throw new Exception ("Conversion failed"); } /*This can be added, based on the type of exception, a bit like case. There are many types of exceptions//system ArgumentNullException//Parameter exception ArgumentOutOfRangeException//Parameter exception DivideByZeroException//divisor is 0 exception IndexOutOfRangeException//Index out of range exception nullreference-exception//parameter exception OverflowException//Overflow exception stackoverflowexception/ /Heap Overflow Exception//system.io directorynotfoundexception//The exception of the path is not found EndOfStreamException//end Stream Exceptions filenotfoundexception// File exception not found Pathtoo-longexception//path too long exception//system.data DuplicateNameException invalidconstrainexception Invalidexpressionexception missing-primarykeyexception nonullallowed-exception ReadOnlyException// System.Runtime.InteropServices invalidcomobjectexception invalidolevarianttypeexception sehexception catch ( Exceptiontype e) {//exception handling}*/ finally{Console.WriteLine (i.ToString ()); } }
Try catch and finally in C #