In C #, What Is throw for? Does it capture exceptions and then pop up the exception dialog box? Like MessageBox. Show? Can it be used together with try and catch? For example:
If (E. clickeditem = print)
{
I = 0;
Try {
If (((form21_activemdichild=.txt main. Text. Length <1)
Return;
This. printdocument1.print ();
}
Catch (exception ERR)
{
Throw new exception ("print error" + err. Message );
// MessageBox. Show ("print error", Err. Message, messageboxbuttons. OK, messageboxicon. Error );
}
}
The above code can be compiled, but when an exception occurs in the running program, the exception dialog box is not displayed, but the program crashes. The error is: Exception Handling
Print error. The object reference is not set to the instance of the object.
Is the throw usage in the code wrong? It cannot be used like this. How should it be used.
Question added:
Well, how can we change it?
Best Answer
New exception is used to create an exception manually. Throw throws this exception.
In this way, we can define the exception information we want.
However, if an exception is thrown, it must be handled. If the exception is not handled, the system will crash.
This is not suitable for you.
For example, the exception throw can be used in this way. I now use the AA method in Class A to call the BB method in instance B. It may be case-insensitive. Let's take a look:
Class
{
Private void AA ()
{
B BB = new B ();
Try // The BB method of B is called here, and the exception thrown by BB is caught and processed at the same time.
{
BB. BB ();
}
Catch (exception E)
{
MessageBox. Show ("Class B error:" + E); // The exception information of BB is processed here.
}
}
}
Class B
{
Int I = 0;
Public void BB ()
{
If (this. I! = 0) // here I made a casual assumption, just look at the meaning to understand it.
{
Throw new exception ("computer fault, I cannot be greater than 0 .");
}
}
}
You should not use throw here. Simply use MessageBox. Show ("print error" + err. Message.