c# - Attrapez plusieurs exceptions à la fois

Mots clés : c#.netexceptionc#

meilleur 5 Réponses c# - Attrapez plusieurs exceptions à la fois

vote vote

92

catch (Exception ex)             {                     if (ex is FormatException || ex is OverflowException)     {         WebId = Guid.Empty;         return;     }          throw; } 
vote vote

80

catch (Exception ex) when (     ex is ...     || ex is ...     || ex is ... ) 
private void TestMethod () {     Action<Exception> errorHandler = ( ex ) => {         // write to a log, whatever...     };      try     {         // try some stuff     }     catch ( FormatException  ex ) { errorHandler ( ex ); }     catch ( OverflowException ex ) { errorHandler ( ex ); }     catch ( ArgumentNullException ex ) { errorHandler ( ex ); } } 
try {     // try some stuff } catch( FormatException ex ){} catch( OverflowException ex ){} catch( ArgumentNullException ex ){} 
// sorta sucks, let's be honest... try {     // try some stuff } catch( Exception ex ) {     if (ex is FormatException ||         ex is OverflowException ||         ex is ArgumentNullException)     {         // write to a log, whatever...         return;     }     throw; } 
// super sucks... catch( Exception ex ) {     if ( ex is FormatException || ex is OverflowException || ex is ArgumentNullException )     {         // write to a log, whatever...         return;     }     throw; } 
vote vote

79

try { … } catch (Exception e) when (MyFilter(e)) {     … } 
private bool MyFilter(Exception e) {   return e is ArgumentNullException || e is FormatException; } 
try { … } catch (Exception e) when (e is ArgumentNullException || e is FormatException) {     … } 
vote vote

63

Catch ex As Exception When TypeOf ex Is FormatException OrElse TypeOf ex Is OverflowException 
Action onError = () => WebId = Guid.Empty; try {     // something } catch (FormatException) {     onError(); } catch (OverflowException) {     onError(); } 
vote vote

56

try {        WebId = new Guid(queryString["web"]); } catch (Exception ex) when(ex is FormatException || ex is OverflowException) {      WebId = Guid.Empty; } 
try {    await Task.WaitAll(tasks); } catch (Exception ex) when( ex is AggregateException ae &&                            ae.InnerExceptions.Count > tasks.Count/2) {    //More than half of the tasks failed maybe..?  } 

Questions similaires