custom Throw() function

N

Nenad Dobrilovic

Hi,
I have function which is throwning exception, like this:

public class LoggedException : Exception
{
public void Throw()
{
throw this;
}
}

I am using like this:

public int fun()
{
if (..)
return 0;
(new LoggedException()).Throw(); <-- Compiler Error CS0161
}

But I get 'Compiler Error CS0161: not all code paths return a value'.
How can I tell to compiler that I don't need return value when I call
Throw() function?
Thank you,
Nenad
 
N

Nicholas Paldino [.NET/C# MVP]

Nenad,

You can not. The compiler doesn't know that the Throw method will
always throw an exception, so you need to place a return statement after the
call to Throw.

Hope this helps.
 
N

Nenad Dobrilovic

Nicholas said:
Nenad,

You can not. The compiler doesn't know that the Throw method will
always throw an exception, so you need to place a return statement after the
call to Throw.

Hope this helps.

Thank you for your quick answer.
I was hoping that I can tell him, beacuse he is not clever enough to
find out by himself.
 
M

mikeb

Nenad said:
Hi,
I have function which is throwning exception, like this:

public class LoggedException : Exception
{
public void Throw()
{
throw this;
}
}

I am using like this:

public int fun()
{
if (..)
return 0;
(new LoggedException()).Throw(); <-- Compiler Error CS0161
}

But I get 'Compiler Error CS0161: not all code paths return a value'.
How can I tell to compiler that I don't need return value when I call
Throw() function?

You have several options:

//Option 1:
public int fun()
{
if (!(..)) {
(new LoggedException()).Throw();
}

// ...
return 0;
}


// Option 2:
public class LoggedException : Exception
{
public LoggedException GetException()
{
return( this);
}
}


public int fun()
{
if (..)
return 0;
throw (new LoggedException()).GetException();
}

//Option 3:
// put whatever logging functionality you would have put
// into Throw() (or GetException()) into the
// LoggedException() constructor and simply do:

throw new LoggedException();
 

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

Top