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

前端 未结 10 2160
说谎
说谎 2020-11-27 04:39

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 sim

10条回答
  •  [愿得一人]
    2020-11-27 05:16

    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(string id)
        {
            var entity = session.Get(id);
            if (entity == null)
                throw GetEntityNotFoundException(typeof(TEntity), id);
            return entity;
        }
    
    

提交回复
热议问题