How to use Java-style throws keyword in C#?

Viewed 73840

In Java, the throws keyword allows for a method to declare that it will not handle an exception on its own, but rather throw it to the calling method.

Is there a similar keyword/attribute in C#?

If there is no equivalent, how can you accomplish the same (or a similar) effect?

10 Answers

If the c# method's purpose is to only throw an exception (like js return type says) I would recommend just return that exception. See the example bellow:

    public EntityNotFoundException GetEntityNotFoundException(Type entityType, object id)
    {
        return new EntityNotFoundException($"The object '{entityType.Name}' with given id '{id}' not found.");
    }

    public TEntity GetEntity<TEntity>(string id)
    {
        var entity = session.Get<TEntity>(id);
        if (entity == null)
            throw GetEntityNotFoundException(typeof(TEntity), id);
        return entity;
    }

For those wondering, you do not even need to define what you catch to pass it on to the next method. In case you want all your error handling in one main thread you can just catch everything and pass it on like so:

try {
    //your code here
}
catch {
    //this will throw any exceptions caught by this try/catch
    throw;
}
Related