« Exception » : différence entre les versions
Apparence
Ligne 22 : | Ligne 22 : | ||
{ | { | ||
ArgumentException.ThrowIfNullOrEmpty(argument1, nameof(argument1)); | ArgumentException.ThrowIfNullOrEmpty(argument1, nameof(argument1)); | ||
ArgumentNullException.ThrowIfNull(argument1, nameof(argument1)); | |||
ArgumentOutOfRangeException.ThrowIfEqual(argument1, "", nameof(argument1)); | |||
ArgumentOutOfRangeException.ThrowIfZero(argument1, nameof(argument1)); | |||
} | } | ||
</kode> | </kode> |
Dernière version du 8 janvier 2025 à 08:57
Liens
Exemple
try { /* ... */ } catch (InvalidCastException icex) { /* ... */ } // exception filter, si le test n'est pas valide: relance l'exception sans modifier la stacktrace catch (Exception ex) when (ex.ParamName == "...") { /* ... */ } catch (Exception ex) { throw; // relance l'exception throw ex; // relance l'exception, mais la stacktrace est écrasée throw new CustomException("Error message", ex); // lance une nouvelle exception avec le précédente exception dans inner exception } |
Argument Exception
public void MyMethod(string argument1) { ArgumentException.ThrowIfNullOrEmpty(argument1, nameof(argument1)); ArgumentNullException.ThrowIfNull(argument1, nameof(argument1)); ArgumentOutOfRangeException.ThrowIfEqual(argument1, "", nameof(argument1)); ArgumentOutOfRangeException.ThrowIfZero(argument1, nameof(argument1)); } |
ExceptionDispatchInfo
Permet de capturer une exception et sa StackTrace pour la relancer ensuite.
catch (Exception ex) { ExceptionDispatchInfo capturedException = ExceptionDispatchInfo.Capture(ex); } if (capturedException != null) { capturedException.Throw(); } |
User-defined exceptions
MyException.cs |
public class MyException : Exception { public MyException() { } public EmployeeListNotFoundException(string message) : base(message) { } public EmployeeListNotFoundException(string message, Exception inner) : base(message, inner) { } } |