Skip to content

Instantly share code, notes, and snippets.

@luisdeol
Created January 28, 2018 15:04
Show Gist options
  • Save luisdeol/df1be4d5af7b3339d1af804d13b49b1f to your computer and use it in GitHub Desktop.
Save luisdeol/df1be4d5af7b3339d1af804d13b49b1f to your computer and use it in GitHub Desktop.
Re-Throwing Exceptions
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