Created
January 28, 2018 15:04
-
-
Save luisdeol/df1be4d5af7b3339d1af804d13b49b1f to your computer and use it in GitHub Desktop.
Re-Throwing Exceptions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| namespace implement_exception_handling | |
| { | |
| class Program | |
| { | |
| static void Main(string[] args) | |
| { | |
| var notSoGreatPhrase = "That is a not-so-great phrase"; | |
| try | |
| { | |
| var phrase1ToInt = int.Parse(notSoGreatPhrase); | |
| } | |
| catch (FormatException) | |
| { | |
| //Use that when you want to log something, you don't really want to change the exception | |
| throw; | |
| } | |
| try | |
| { | |
| var phrase2ToInt = int.Parse(notSoGreatPhrase); | |
| } | |
| catch (FormatException exception) | |
| { | |
| // THrow a new exception, but add the original as a parameter. | |
| // You keep the information about the original exception | |
| throw new NotSoGreatException("Not-so-great Exception", exception); | |
| } | |
| try | |
| { | |
| var phrase3ToInt = int.Parse(notSoGreatPhrase); | |
| } | |
| catch (FormatException) | |
| { | |
| // Throwing the same exception does not really help a lot, since it cleans the call stack and make | |
| // harder to debug the code | |
| throw new FormatException("Throwing the same exception"); | |
| } | |
| Console.ReadKey(); | |
| } | |
| public class NotSoGreatException : Exception | |
| { | |
| public NotSoGreatException(string message, Exception exception) : base(message, exception) | |
| { | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment