473,325 Members | 2,816 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,325 software developers and data experts.

Try Catch with Inheritance problem.

110 100+
I am have some code where I pass in a value for an employees salary as a negative. Using try catch it tries passing this negative value into my emp.salary where there is a test statement saying if salary is less then 0 then throw a NegativeSalaryException.
Expand|Select|Wrap|Line Numbers
  1. using System;
  2. public class DebugNine03
  3. {
  4.    public static void Main()
  5.    {
  6.       Employee emp = new Employee();
  7.  
  8.       try
  9.       {
  10.          emp.IdNum = 234;
  11.          emp.Salary = -12;
  12.       }
  13.       catch (NegativeSalaryException)
  14.       {
  15.          Console.WriteLine(emp.);
  16.          Console.WriteLine(Environment.StackTrace);
  17.       }
  18.    }
  19. }
  20. public class NegativeSalaryException : Exception
  21. {
  22.    private static string msg = "Employee salary is negative.";
  23.    public NegativeSalaryException() : base()
  24.    {
  25.    }
  26. }
  27.  
  28. public class Employee
  29. {
  30.    public int idNum;
  31.    public double salary;
  32.    public int IdNum
  33.    {
  34.       get
  35.       {
  36.          return idNum;
  37.       }
  38.        set
  39.        {
  40.            idNum = value;
  41.        }
  42.    }
  43.    public double Salary
  44.    {
  45.       get
  46.       {
  47.          return salary;
  48.       }
  49.       set
  50.       {
  51.         if(value < 0)
  52.         {
  53.            NegativeSalaryException salExcep = new NegativeSalaryException();
  54.            throw(salExcep);
  55.         }
  56.         salary = value;
  57.       }
  58.    }
  59.  
  60. }
  61.  
I know that because the salary passed is negative always it is supposed to always have the negativesalary exception occur but I don't understand what the throw statement is doing?

I am also having issues understanding how to use the value "msg" declared in my NegativeSalaryException inside my Main method.

If anyone has any thoughts on it I would be greatly appreciative. Thanks.
Nov 4 '10 #1
3 2736
GaryTexmo
1,501 Expert 1GB
You're close but missing a few things. I'd highly recommend you read the following, there's some good information there.

http://msdn.microsoft.com/en-us/libr...8VS.80%29.aspx

In your case, there's a few key things wrong with your code.

1) You've got some text in your exception that you're calling the message, but you're not actually doing anything with it. I'm guessing you want this to be the exception message text when no other text is specified? In this case, you can just pass that message along to the appropriate base constructor...

Expand|Select|Wrap|Line Numbers
  1. public NegativeSalaryException()
  2.   : base (msg)
  3. {
  4. }
You may also want to consider exposing the constructor that takes a string as a parameter, so users of the exception can specify their own message.

Expand|Select|Wrap|Line Numbers
  1. public NegativeSalaryException(string message)
  2.   : base (message)
  3. {
  4. }
2) When you throw your exception, you aren't providing a message. This kind of ties in with the above... but the general method of throwing an exception is to provide some text with it. For example, if I were throwing a generic exception I'd do something like this...

Expand|Select|Wrap|Line Numbers
  1. public static float Divide(float numerator, float denominator)
  2. {
  3.   if (denominator == 0)
  4.     throw new Exception("Cannot divide by zero!");
  5.  
  6.   return numerator / denominator;
  7. }
We provide this so the user gets some feedback as to what went wrong. To correct that, either do as mentioned in the above, or provide an exception message for your exception at the time it is thrown.

3) Last one, and this is more of a suggestion than a requirement. When you catch an exception, I personally find it helpful to provide an exception parameter so you can access information about the exception. With what you have, you're just catching the exception type, but the actual exception is lost. You can access this simply by providing a variable name for the exception...

Expand|Select|Wrap|Line Numbers
  1. try
  2. {
  3.   // some code
  4. }
  5. catch (Exception e)
  6. {
  7.   Console.WriteLine("An exception occurred!");
  8.   Console.WriteLine(e.Message);
  9.   Console.WriteLine(e.StackTrace);
  10. }
Hopefully that helps. As always, I'd recommend reading the MSDN doc on this or checking out a few tutorials on exception handling. They provide much more comprehensive information than I can :) Good luck!
Nov 4 '10 #2
Fuzz13
110 100+
GaryTextmo You are just a king among men. You help me on so many of my projects so a personal thanks for that. I tried passing the msg string back thru the base
Expand|Select|Wrap|Line Numbers
  1.    public NegativeSalaryException() : base(msg)
  2.  
But how do I use that in my main method now. Or just get it to show that string known as "msg" when the exception occurs? I tried calling it in my console.writeline statement but it can't find it?
Nov 4 '10 #3
GaryTexmo
1,501 Expert 1GB
Read the MSDN for an Exception class:
http://msdn.microsoft.com/en-us/libr...exception.aspx

Take note of the constructor section, specifically:
http://msdn.microsoft.com/en-us/library/48ca3hhw.aspx

Under remarks: This constructor initializes the Message property of the new instance using the message parameter.

You should now be able to access the message in your catch statement using the Message property.

That particular bit of code you have in your post is just a means of setting a default message when one isn't provided, which is what I gathered you wanted to do from the code you wrote in your original post. As I noted in my second code block, you can also create a constructor to pass a string parameter instead of a constant default message if desired.

Using the code we've created thus far...
Expand|Select|Wrap|Line Numbers
  1. // Create an exception with the default message
  2. NegativeSalaryException nse1 = new NegativeSalaryException();
  3.  
  4. // Create an exception with a specific message
  5. NegativeSalaryException nse2 = new NegativeSalaryException("Something bad has happened and I'm pretty sure it's a negative salary, but hey, who knows, right!?");
Were you to throw each of those, wrapped in a try/catch block, you could output the Message property to see what it was.
Nov 4 '10 #4

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

Similar topics

3
by: Mark A. Gibbs | last post by:
Good day, i'm having a bit of trouble with a base class i'm working on. this is what it boils down to: template <typename T> class foo { protected: foo() { T* p = static_cast<T*>(this); }
9
by: vidalsasoon | last post by:
Ok, this is the structure of my classes. " class Global " | " ------------------------------------------- " | ...
3
by: Darren | last post by:
I have a Person object and from that I'm inheriting other objects including Client, Carer, Doctor (and others). The Person object has a large number of properties and methods that I want available...
1
by: Michael | last post by:
Hello, I'm trying to implement sample I found on page templates, so I do not have to maintain "<html><head>..." on all my documents. But don't let that confuse you, this is an inheritance...
0
by: Mariano | last post by:
Hi, I have posted a bug of the forms designer that overwrites always the Icon, thus preventing Icon inheritance when you derive from a form. I am trying to overcome this by adding an ImageList in...
3
by: guy | last post by:
I have a problem with a class hierarchy. The inheriting and inherited class are in different solutions. In the base class, (which inherits from System.Windows.Forms.UserControl) i have a method...
9
by: surendran.d | last post by:
hi, can diamond inhertance problem be solved using virtual functions,, or can only be done with scope resolution operators.. is there any other way to solve this problem... Thanks, suri
4
by: amidzic.branko | last post by:
I'm trying to solve a problem using inheritance and polymorphism in python 2.4.2 I think it's easier to explain the problem using simple example: class shortList:
8
by: Hans-Dieter Dreier | last post by:
Hi NG, I have an inheritance like this: class a_interface { virtual bool x() = 0; }; class a_version_1 : public a_interface
3
by: Leo Seccia | last post by:
Hello everyone, I have a c# project with a sql server database. I have a number of lookup tables in my database which I successfully managed to import into my LINQ dataclasses. eg. Table:...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

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.