2017-09-25 89 views
-4

具有特定異常類的主要優點是什麼,因爲我們可以在System.Exception類中擁有所有異常。 爲什麼會使用特定的錯誤處理類?C#異常處理特定類

+3

剛剛出來面試? –

+0

答案真的取決於你的需求 - 有時候你需要更細緻的東西。 –

+3

[我們什麼時候應該創建自己的java異常類?]的可能的重複(https://stackoverflow.com/questions/22698584/when-should-we-create-our-own-java-exception-classes) –

回答

1

異常處理程序按類別工作。如果你只有一個例外類,你可以這樣做:

try 
{ 
    //Do something that might raise different types of exceptions 
} 
catch(ArgumentException e1) //Catch any exception that is an ArgumentException or one its derived types 
{ 
    //Do something to handle the invalid argument 
} 
catch(NetworkException e2) //Catch any exception that is a NetworkException or one of its derived types 
{ 
    //Do something to handle the issue with the network 
} 
catch(Exception e3) 
{ 
    //Do something to log the unexpected exception 
    throw; 
} 

注意you should not catch the base exception,除非你正在做的唯一事情就是登錄並重新拋出。