0

In Java i can explicitly specify that a method throws an exception like:

public void read() throws IOException{}

What is the c# equivalent of this?

What are the best practices for throwing custom exceptions?

I have made them serializable and provided a streaming context also .

6
  • 1
    No, that's not how you throw an exception in Java. That's how you declare a method that throws an exception. Commented Sep 3, 2011 at 17:34
  • 1
    That an exception specification. It is widely considered to be a mistake, C# doesn't have it and it is deprecated in C++. Commented Sep 3, 2011 at 17:36
  • my bad what i meant was how do i declare a method that throws an exception in C#..i apologise... Commented Sep 3, 2011 at 17:38
  • oki.so exception specification is a bad idea.. now for e.g. so how do i ask the caller to handle an exception that was thrown by his bad parameters ? Commented Sep 3, 2011 at 17:42
  • 1
    throw new Exception() -> throws an exception 2 caller. throw new ArgumentException() ->a standard in framework. Or you can customize this Commented Sep 3, 2011 at 17:55

2 Answers 2

6

What you're referring to is the actual documentation of code that throws exceptions.

Read this thread that discusses this question: How to document thrown exceptions

Sign up to request clarification or add additional context in comments.

2 Comments

@ashutosh What do you want then? in C# you can only document what exceptions a method throws. You can't make them a part of the signature of the method. Ie there's no way of having the compiler tell the caller of a method that he didn't handle specific exceptions. He can read the documentatio if such exist or figure it out at run time
@Rune FS ,@liortal yes ,i had a closer look at the exception specification for C#,it seems i just have to specify in the documentation what exceptions my method might throw and have the caller handle it . thanks for your help.
1

The topic in MSDN called Exceptions and Exception Handling covers Creating and Throwing Exceptions in detail.

However, exception specifications are not part of the C# language like they are in Java. You must rely on documentation to tell the user of your API what exceptions may be thrown. You cannot force a user to handle an exception, or document it in code.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.