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

前端 未结 10 2096
说谎
说谎 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:15

    You are asking about this :

    Re-throwing an Exception

    public void Method()
    {
      try
      {
          int x = 0;
          int sum = 100/x;
      }
      catch(DivideByZeroException e)
      {
          throw;
      }
    }
    

    or

    static void Main() 
        {
            string s = null;
    
            if (s == null) 
            {
                throw new ArgumentNullException();
            }
    
            Console.Write("The string s is null"); // not executed
        }
    
    0 讨论(0)
  • 2020-11-27 05:15

    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;
    }
    
    0 讨论(0)
  • 2020-11-27 05:16

    Yes this is an old thread, however I frequently find old threads when I am googling answers so I figured I would add something useful that I have found.

    If you are using Visual Studio 2012 there is a built in tool that can be used to allow for an IDE level "throws" equivalent.

    If you use XML Documentation Comments, as mentioned above, then you can use the <exception> tag to specify the type of exception thrown by the method or class as well as information on when or why it is thrown.

    example:

        /// <summary>This method throws an exception.</summary>
        /// <param name="myPath">A path to a directory that will be zipped.</param>
        /// <exception cref="IOException">This exception is thrown if the archive already exists</exception>
        public void FooThrowsAnException (string myPath)
        {
            // This will throw an IO exception
            ZipFile.CreateFromDirectory(myPath);
        }
    
    0 讨论(0)
  • 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<TEntity>(string id)
        {
            var entity = session.Get<TEntity>(id);
            if (entity == null)
                throw GetEntityNotFoundException(typeof(TEntity), id);
            return entity;
        }
    
    
    0 讨论(0)
  • 2020-11-27 05:18

    Actually not having checked exceptions in C# can be considered a good or bad thing.

    I myself consider it to be a good solution since checked exceptions provide you with the following problems:

    1. Technical Exceptions leaking to the business/domain layer because you cannot handle them properly on the low level.
    2. They belong to the method signature which doesn't always play nice with API design.

    Because of that in most bigger applications you will see the following pattern often when checked Exceptions occur:

    try {
        // Some Code
    } catch(SomeException ex){
        throw new RuntimeException(ex);
    }
    

    Which essentially means emulating the way C#/.NET handles all Exceptions.

    0 讨论(0)
  • 2020-11-27 05:20

    The op is asking about the C# equivalent of Java's throws clause - not the throw keyword. This is used in method signatures in Java to indicate a checked exception can be thrown.

    In C#, there is no direct equivalent of a Java checked exception. C# has no equivalent method signature clause.

    // Java - need to have throws clause if IOException not handled
    public void readFile() throws java.io.IOException {
      ...not explicitly handling java.io.IOException...
    }
    

    translates to

    // C# - no equivalent of throws clause exceptions are unchecked
    public void ReadFile() 
    {
      ...not explicitly handling System.IO.IOException...
    }
    
    0 讨论(0)
提交回复
热议问题