473,809 Members | 2,776 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to throw an exception?

Tyler Wiebe
66 New Member
This is my first time using exceptions, and I can't seem to make the exception get thrown. This is meant for painting this shape on the form. If I have the curve height more then the height of the object, all my form does is creates red X's for all of the controls.

So what am I doing wrong?

P.S. It works fine if the curve height is less then the object height.

Expand|Select|Wrap|Line Numbers
  1.     public class BottomCurve
  2.     {
  3.         public BottomCurve(int Width, int Height, int CurveHeight)
  4.         {
  5.             if (CurveHeight >= Height) throw new System.Exception("The curve height cannot be greater then or equal to the height of this object");
  6.  
  7.             this.ISize = new System.Drawing.Size(Width, Height);
  8.  
  9.             this.ICurve = new System.Drawing.Point[]
  10.             {
  11.                 new System.Drawing.Point(0, this.Height),
  12.                 new System.Drawing.Point(this.Width / 2, this.Height - CurveHeight),
  13.                 new System.Drawing.Point(this.Width, this.Height)
  14.             };
  15.  
  16.             this.IGraphicsPath = new System.Drawing.Drawing2D.GraphicsPath();
  17.             this.IGraphicsPath.StartFigure();
  18.  
  19.             this.IGraphicsPath.AddLine(0, 0, 0, this.Height);
  20.             this.IGraphicsPath.AddCurve(ICurve);
  21.             this.IGraphicsPath.AddLine(this.Width, this.Height, this.Width, 0);
  22.             this.IGraphicsPath.AddLine(this.Width, 0, 0, 0);
  23.  
  24.             this.IGraphicsPath.CloseFigure();
  25.         }
  26.  
  27.         internal System.Drawing.Point[] ICurve;
  28.         internal System.Drawing.Drawing2D.GraphicsPath IGraphicsPath;
  29.         public System.Drawing.Drawing2D.GraphicsPath GraphicsPath { get { return this.IGraphicsPath; } }
  30.  
  31.         internal System.Drawing.Size ISize;
  32.         public System.Drawing.Size Size { get { return this.ISize; } }
  33.         public int Width { get { return this.Size.Width; } }
  34.         public int Height { get { return this.Size.Height; } }
  35.     }
  36.  

HOW TO USE:

Expand|Select|Wrap|Line Numbers
  1.         public void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
  2.         {
  3.             BottomCurve BC = new BottomCurve(this.Width, 100, 40);
  4.             e.Graphics.FillPath(new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(255, 255, 0, 0)), BC.GraphicsPath);
  5.         }
  6.  
Oct 24 '11 #1
1 1817
GaryTexmo
1,501 Recognized Expert Top Contributor
You get that red X when an unhandled exception occurs in a paint. It appears to be how the .NET framework handles it. It also looks like when an unhandled exception occurs, you can't really recover from it. I took your code and had the curve height set by a variable that I incremented to / decremented from with buttons and once it went into an unhandled exception it didn't come back, even if I reduced the curve height.

Anyway, this unhandled exception is entirely your doing :D On line 5 of your code above, you're throwing an exception when the curve height is greater than the height... which you intend, but what you're not doing is catching that exception anywhere. This is where the try/catch block comes in... you attempt something and if there's an exception, you handle it appropriately. I made the following changes to your paint method:

Expand|Select|Wrap|Line Numbers
  1. protected override void OnPaint(PaintEventArgs e)
  2. {
  3.     base.OnPaint(e);
  4.  
  5.     try
  6.     {
  7.         BottomCurve curve = new BottomCurve(this.Width, this.Height / 2, m_curveHeight);
  8.         e.Graphics.FillPath(new SolidBrush(Color.Yellow), curve.GraphicsPath);
  9.     }
  10.     catch (Exception ex)
  11.     {
  12.         e.Graphics.DrawString(ex.Message, this.Font, Brushes.Red, new PointF(0f, (float)this.Font.Height));
  13.     }
  14.  
  15.     e.Graphics.DrawString("Curve Height: " + m_curveHeight.ToString(), this.Font, Brushes.Black, new PointF(0f, 0f));
  16. }
Here I'm putting the curve instantiation inside a try/catch block. If there's an exception, I output an error message. If there's no exception, the try block executes completely and will draw the curve.

There is something you should be aware of though. There is an overhead associated with exception handling and while today's processors handle it fairly well, you may want to consider a more efficient approach. There are two places I can see where you can immediately increase your efficiency.

1) Instead of having a curve generated in the constructor so that you need to make a new curve every cycle, consider instantiating a single curve object and then updating it. There's overhead associated with creating, and subsequently destroying, an object. When you do this in a draw loop (assuming you have a draw loop) you're causing needless object creations which will only get released for garbage collection immediately. So instead of doing that work in the constructor, maybe move it to a GenerateCurve method which takes the same parameters. When called, it will update the class members and regenerate the curve.

2) Instead of an exception, consider a return value. If the curve generation sees anything it doesn't like, it can just return false. On the drawing side, if a return value of false is seen the appropriate action can be taken. This does take away from the error messages that can be seen though, but you can do other things like return a string instead of a boolean. If the string is empty, curve generation was successful. This might not be preferable to you though.

As I mentioned, today's processors can handle exception handling fairly well so the second one isn't that big a deal. Actually neither are, but they are something to consider if you're going to have a high drawing demand. If not, carry right on :)
Oct 24 '11 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

0
5156
by: arun gunda | last post by:
I want to throw exception dynamically. This what I want to do For example I want to throw System.Net.WebException exception. I will know the full exception name at run time, can I create a exception and throw it. I know how to do it if we hardcode the exception
3
458
by: Kerri | last post by:
Hi, I am new to .NET In my Error Logic on my Aspx pages when an error happens it hits my catch statement where I throw an Exception. My question is : what is the difference between Thwo Exception and Throw
2
1579
by: Dave | last post by:
Josuttis states that I may not throw an exception of type exception or of one of the standard exception types used for language support. Where in the Standard am I forbidden from "throw exception();"? Thanks, Dave
2
2541
by: TS | last post by:
i'm wondering if it is preferred practice to throw exception in this circumstance. I have seen it done like that, but i have also read that you should try to never throw an exception in circumstances where you can do some test before the operation that would throw the test so that you can by pass the exception handling which is an expensive operation. So lets say the scenario is i have an object that is validating itself in the business...
1
1353
by: z. f. | last post by:
in vb asp.net page i'm overriding the finalize method in order to make cleanup. if i throw exception there it is not seen on the page. probably because the page has already sent to the client. is there a way to throw exception on the finalize method in order to check that objects were closed, but how do i trace this exception? TIA, z.
3
14809
by: Ryan Liu | last post by:
Hi, In the .NET Framework SDK documentation, I can see DataRow.AcceptChanges method will throw RowNotInTableException exeception. And in DataTable.AcceptChanges(), the documentation does not mention it will throw any exception, but in my code (multi-thread), I see it throw exceptions at two situations: dr = this.currentQuotaUserDt.NewRow();
5
1596
by: Rob Dob | last post by:
I am trying to set the NullValue within the Column properties of my Dataset in VS2005. The DataType is a System.DateTime. and when I try and change it from "(Throw Exception)" I get the following error: For columns not defined as System.String, the only valid value is (Throw exception). The Datafield is a datetime that allows nulls, if I don't set this value then when I try save changes to this field within my form I get it...
0
1039
by: Steve B. | last post by:
Hi, I'm wondering how to correctly throw exception within ASP.Net pages. I've page wich which waits for an "id" parameter in the querystring. I want to validate this param. I've wrote this code : if (Page.Request.QueryString == null)
1
1779
by: =?Utf-8?B?TVIgRQ==?= | last post by:
This may seem like a stupid question but in C#: Say for instance I have a set of SQL processes that I run via ExecuteReader(). These processes return several pieces of information to the DataReader, including any SQL exception that occurred (This may include messages I generated b/c something didn’t check out based on programmed requirements, but its not a runtime exception as far as SQL or C# is concerned). I then check this...
4
2236
by: George2 | last post by:
Hello everyone, In Bjarne's book, it is mentioned that sort of STL may throw exception, like sorting elements in a vector. In what situation will sort throw exception? I can not find a case. thanks in advance,
0
9603
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10376
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10120
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9200
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6881
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4332
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3861
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3015
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.