Solved

Trying to use a Custom Exception object..

Posted on 2011-03-22
6
266 Views
Last Modified: 2012-05-11
Hi Guys =)

I'm having problems trying to implement a custom exception object.  The code below, which generates a 'divide by zero' error does not get passed to the custom exception object, instead will i'm stepping through the code it will just stop on the divide by zero line of code and simple display my error in a Visual Studio error box, never goes into the Catch..

If I simply replace the two instances of "catch (CustomeException ex)"  with "catch (Exception ex)" then the catch will pass the error into the default exception object.

Any suggestions?

Thanks in advance =)


-------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ErrorTrappingTest
{
    public class MyFunctions
    {
         
            public bool Method1()
            {
                try
                {
                    bool result = Method2();
                }
                catch (CustomException ex)
                {
                    throw;
                }
                return true;            
            }


            public bool Method2()
            {
                try
                {
                    int a = 5, b = 0;
                    int x = a / b;   // Causes a divide by zero error
                }
                catch (CustomException ex)
                {
                    throw;
                }

                return true;        
            }


             public class CustomException : System.Exception
            {
                public CustomException() : base() { }
                public CustomException(string message) : base(message) { }
                public CustomException(string message, System.Exception inner) : base(message, inner) { }

            }


       
    }
}
0
Comment
Question by:aamado
  • 2
  • 2
  • 2
6 Comments
 
LVL 11

Expert Comment

by:Sudhakar Pulivarthi
ID: 35190135
Hi,
You can use as below if are planning to implement Custom Exception to use all over ur application. But pain here is you need to know and catch all system exceptions and catch them and throw the custom exception with more info on the exception scenario.
Here is an modified example:
  public bool Method2()
            {
                try
                {
                    int a = 5, b = 0;
                    int x = a / b;   // Causes a divide by zero error
                }
                catch (DivideByZeroException ex)
                {
                    throw new CustomException("Divide by Zero error occured");
                }

                return true;        
            }
Note: It is better it check for this exception occuring variable check before performing like:
 int x;
if(b> 0)
{
 x = a / b;
}
else
{
throw new CustomException("Invalid value for b is provided");
}
0
 
LVL 11

Expert Comment

by:Sudhakar Pulivarthi
ID: 35190160
Here is more info on exception handling:
http://msdn.microsoft.com/en-us/library/ms173160.aspx
0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 35190271
You cannot use a custom exception to arbitarily catch other exceptions. Simply adding
catch (CustomException ex)
{
}

Open in new window

Will not automatically convert the DivideByZeroException into your custom type. You still need to catch the DivideByZeroException, and then throw your custom exception instead, if that is what you choose to do.
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:aamado
ID: 35190769
Thanks Sudhakar and Carl =)

Carl, I think I get what you're saying..  I was hoping I could just inherit from Exception and thus allow my custom exception to grab any exception type the way the base exception class can.  

My ultimate goal was to extend the base Exception class so that I could add other properties to it.  I think i'm taking the wrong approach..
0
 
LVL 52

Accepted Solution

by:
Carl Tawn earned 125 total points
ID: 35190800
You can still do that. But if you want to handle existing exception types then you need to catch the more generic Exception and then create and throw your custom exception.
0
 

Author Comment

by:aamado
ID: 35190961
Got it!   Your explanation made it click for me finally!

I modified it this way (and added the properties 'Message' and ''Note" to my custom exception class)  and it is working.

Thanks for your help!

-Alan

--------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ErrorTrappingTest
{
    public class MyFunctions
    {
       
            public bool Method1()
            {
                try
                {
                    bool result = Method2();
                }
                catch (CustomException ex)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    throw;
                }
           
                return true;            
            }


            public bool Method2()
            {
                try
                {
                    int a = 5, b = 0;
                    int x = a / b; // Causes error
                }
                catch (Exception ex)
                {
                    CustomException customException = new CustomException();
                    customException.Message = ex.Message;
                    customException.Note = "test";

                    throw customException;
                }

                return true;        
            }


             public class CustomException : System.Exception
            {
                public CustomException() : base() { }
                public CustomException(string message) : base(message) { }
                public CustomException(string message, System.Exception inner) : base(message, inner) { }

                public string Message;
                public string Note;


            }


       
    }
}
 
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
C# Error - Add Failed 12 78
Authentication of Web Services 3 54
VB.Net How to Exit Sub - Exit Form??? 5 51
Interview questions for support of a legacy ASP.NET site 4 40
Introduction                                                 Was the var keyword really only brought out to shorten your syntax? Or have the VB language guys got their way in C#? What type of variable is it? All will be revealed.   Also called…
Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.
As a trusted technology advisor to your customers you are likely getting the daily question of, ‘should I put this in the cloud?’ As customer demands for cloud services increases, companies will see a shift from traditional buying patterns to new…

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now