when
Clause6 Prior to C# 6, you could catch an exception based only on its type. C# 6 introduces exception filters that enable you to catch an exception based on a catch
’s exception type and a condition that’s specified with a when
clause, as in
catch(ExceptionType name) when(condition)
You also can specify an exception filter for a general catch
clause that does not provide an exception type. This allows you to catch an exception based only on a condition, as in
catch when(condition)
In each case, the exception is caught only if the when
clause’s condition is true
; otherwise, the exception is not caught and the search for an appropriate catch
continues.
A typical use of an exception filter is to determine whether a property of an exception object has a specific value. Consider an app that connects to a web server to download videos. Such an app would call methods that may throw HttpException
s—for example, the web server might not be found, you might not have permission to access the web server, etc. Class HttpException
has an ErrorCode
property that contains a numeric code, which apps can use to determine what went wrong and handle the exception accordingly. The following catch
handler catches an HttpException
only if the exception object’s ErrorCode
property contains 401
, indicating your app does not have permission to access the web server:
catch (HttpException ex) when (exception.ErrorCode == 401)
You might provide several similar catch
handlers with exception filters that test for various other ErrorCode
s.
Following a try
block with multiple catch
clauses for the same type results in a compilation error, unless they provide different when
clauses. If there are multiple such catch
es and one does not have a when
clause, it must appear last; otherwise, a compilation error occurs.