C # Throw usage

Source: Internet
Author: User
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.
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.