2

Possible Duplicate:
how to use Java-style throws keyword in C#?

I am on a work placement at the moment, and doing c#. I am 1 year away from finishing uni where we have predominantly been taught Java.

If I was going to throw a checked exception in Java I would use:

public void saveToFile(String fileName) throws IOException

Is there similar syntax in C# for doing this but for my own custom exception?

Thanks

Community
  • 1
  • 1
ricki
  • 367
  • 2
  • 4
  • 6

2 Answers2

4

In c#, you don't declare the exception that a function may throw. You declare a function regularely:

public void saveToFile( string fileName ) {
    ....
}

Throwing an exception is very easy. There are many predefined exception (such as System.IO.IOException), which you can throw:

using System.IO

...

public void saveToFile(* string fileName ) {

    ...
    throw new IOException( )
}

If you want to throw a custom exception, you have to declare it, and make sure it derives from System.Exception class. You exception class can have any constructor, property or member that you want. e.g.

public class MyException :Exception
{
    public int code { get; set; }
    public MyException(int c) { code = c; }
}

Then, in your code you'll simply throw an instance of it:

...
throw new MyException( 666 );
Uri London
  • 10,631
  • 5
  • 51
  • 81
0

Noop. You just have to catch and throw. Or wrap it into a new exception and throw.

public void saveToFile(string fileName)
{  
    try
    {
        // your code
    }
    catch(Exception ex)
    {
        throw;
        //or: throw new Exception("Whoops", ex);
    }
}
Kees C. Bakker
  • 32,294
  • 27
  • 115
  • 203