The model to use the. NET exception capture mechanism is very simple, see the followingCode
Try
{
If (Somecodition)
Throw Exception;
Else
// Do somthing else
}
Catch (Exception E)
{
//Do something
}
Finally
{
}
Exception Handling isC #Provides a mechanism to handle errors. It provides a custom processing method for each error scenario, and separates the code that identifies the error from the code that handles the error.
In short, known or unknown errors can be properly handled through the exception capture mechanism.
Here we will introduce a little tips for exception capture.
// Scan Port
Int Istart = ( Int ) This . Numericupdown1.value;
Int Iend = ( Int ) This . Numericupdown2.value;
Try
{
This . Progressbar1.minimum = Istart;
This . Progressbar1.maximum = Iend;
This . Richtextbox1.text = " Program starts scanning port: \ n " ;
This . Richtextbox1.update ();
For ( Int I = Istart; I < Iend; I ++ )
{
This . Progressbar1.value = I;
Tcpclient mytcp = Null ;
Try
{
Mytcp = New Tcpclient ( This . Textbox1.text, I );
This . Richtextbox1.text + = " Port " + I. tostring () + " Open! \ N " ;
This . Richtextbox1.update ();
}
Catch
{
}
}
This . Richtextbox1.text + = " The scan port is over! \ N " ;
}
Catch (Exception ERR)
{
MessageBox. Show ("An error occurred while performing port scan. The error message is:"+Err. Message,"Information prompt", Messageboxbuttons. OK, messageboxicon. information );
}
}
The above code has two levels of try-catch. Let's look at the layer inside, and we find that the catch layer inside is not processed,
That is to say, exceptions in the try statement block will be caught here, that is, exceptions in instantiating a tcpclient object.
We know that to instantiate a tcpclient object, two parameters are required: The first IP address and the second port number. The two parameters are combined to indicate a network device.
If the port is occupied, we cannot instantiate our tcpclient object. Of course, an exception is thrown. At this time, the exception is caught by the try-catch on the inner layer, soProgramIt will not interrupt its running status, and continue to execute our unfinished for loop.
That is why our port scanning program has an effect.
As you may think, is there a lot of other points worth using this clever method?
In my previous example, I used this method to determine whether the characters are legal.
Of course, in some specific occasions, you may find that such tips are more useful!
In the end, it is worth noting that, based on my experience, this practice is sometimes at the cost of time consumption, and everyone chooses it with caution!