简体   繁体   中英

How to check if a function throws an exception in c#?

How to check if a function throws an exception in c#?

public List<string> GetFileNames()
{
    try
    {
        // do something
        // return something
    }
    catch(Exception ex)
    {
        // do something
        // log something
    }
}

then i will call GetFileNames() somewhere in my code, but I want to check if it throws an exception, like,

var list = GetFileNames(); // can be 0 count

if(GetFileNames() throws an error)
{
    DoThisMethod()
}
else
{
    DoThisOtherMethod();
}

You have a lot of options here:

  • This is generally done with a Try... pattern like TryParse .

     bool TryGetFileNames(out List<string> fileNames) 
  • You can also return null .

I think you can make it simpler:

public void ICallGetFileNames() 
{
    var list = new List<YourObject>(); 
    try 
    {
        list = GetFileNames();
        DoThisOtherMethod();
    }
    catch (Exception ex) 
    {
        DoThisMethod();
    }        
}

This way, if the exception is thrown by your GetFileNames method, the DoThisOtherMethod() won't be called, since your code is going directly to the Exception block. Otherwise, if no exception is thrown, your code will call the DoThisOtherMethod just after the GetFileNames method.

The fundamental problem is that you're attempting to handle an exception when you're not able to do so.

If GetFilenames cannot recover from the exception, it should throw an exception itself. That may be by omitting a try/catch entirely, or by catching it, wrapping and re-throwing.

public List<string> GetFilenames() {
    try {
        ...
    } catch (Exception e) {
        throw new FileLoadException("Failed to get filenames", e);
        // Or if you don't want to create custom exceptions, perhaps use an InvalidOperationException
    }
}

Failing that, if you don't actually need to abstract the functionality, don't catch the exception in GetFilenames at all, then call it like this:

try {
    var list = GetFilenames()
    DoSomething();
} catch (Exception e) {
    DoSomethingElse();
}

You can"t do this in c#.

The closest thing to what you are describing is the "checked exceptions" which are implemented in java. In such case the function will declare it is throwing some exception like so :

public void foo() throws IOException {
  // your code
}

At compile time you will be forsed to take care of this by either enclosing this in TryCatch block or propagate this the same way in your function.

In c# enclose the function in TryCatch block and use different function in case of faliure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM