won't catch my custom exception

R

rodchar

hey all,

i have a very simple custom exception class:

public class EmptyRecordException : Exception
{
string message;

public override string Message
{
get
{
return message;
}
}

public EmptyRecordException(string message)
{
this.message = message;
}
}


Here's how i try to throw it:

public void ThrowMockException()
{
throw new EmptyRecordException("message from c2");
}



i'm trying to catch it this way:

catch (EmptyRecordException ex)
{
throw ex.Message;
}

but it is giving me an error saying:
The type caught or thrown must be derived from System.Exception

any ideas?

thanks,
rodchar
 
W

Wolfgang Kluge

Hi,

the error is in the line:

throw ex.Message;

Here you want to throw a System.String instead of an object of type
System.Exception...

greets and sorry for my bad english, Wolfgang Kluge
http://gehirnwindung.de/
http://klugesoftware.de/


----- Original Message -----
From: "rodchar" <[email protected]>
Newsgroups: microsoft.public.dotnet.languages.csharp
Sent: Thursday, July 02, 2009 4:22 PM
Subject: Re: won't catch my custom exception
 
H

Hans Kesting

rodchar used his keyboard to write :
can i please ask why?

The "it" that was giving the error apparently was the compiler (not the
runtime). And the line it was complaining about was not the declaration
of your exception, but the "throw ex.Message" statement.
And the compiler was complaining because Message is a string, not an
exception. So you can solve the issue by just using "throw ex".
and does my custom exception class look correct?

Looks ok, but you don't need to override Message (unless you have other
plans). Rewrite the constructor as:

public EmptyRecordException(string message)
: base(message)
{
}

The ": base(message)" calls the base constructor, which will set the
Message property for you.

Hans Kesting
 
A

Armen Kirakosyan

Because you should throw Exception , but not the Message of that Exception
 
R

rodchar

thanks everyone for the help,
rod.

Wolfgang Kluge said:
Hi,

the error is in the line:

throw ex.Message;

Here you want to throw a System.String instead of an object of type
System.Exception...

greets and sorry for my bad english, Wolfgang Kluge
http://gehirnwindung.de/
http://klugesoftware.de/


----- Original Message -----
From: "rodchar" <[email protected]>
Newsgroups: microsoft.public.dotnet.languages.csharp
Sent: Thursday, July 02, 2009 4:22 PM
Subject: Re: won't catch my custom exception
 
A

Arne Vajhøj

rodchar said:
thanks everyone for the extra insight, i appreciate it much,

C# is not like C++ - you can only throw instances of Exception and
sub classes (or null) - you can not throw instances of an arbitrary
type.

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top