Skip to content

Instantly share code, notes, and snippets.

@dnasca
Created March 17, 2015 06:29
Show Gist options
  • Select an option

  • Save dnasca/3db7db96a38cec91851b to your computer and use it in GitHub Desktop.

Select an option

Save dnasca/3db7db96a38cec91851b to your computer and use it in GitHub Desktop.
using System;
using System.IO;
/* Inner Exception Notes
*
* The InnerException property returns the Exception instance that caused the current exception
*
* To retain the original exception, pass it as a parameter to the constructor of the current exception
*
* Always check if the inner exception is not null before accessing any property of the inner exception object -- else, you may get a Null Reference Exception
*
* To get the type of InnerException, use the GetType() method
*
* If you want to intentioanlly throw an exception, you use the 'throw' keyword
*
*
* !@!@ Interview Questions !@!@
* Q. What is an inner exception?
* A. The InnerException property returns the Exception instance that caused the current exception.
* The InnerException will actually give you the original exception which caused the current exception.
* For this to happen, you need to pass the original exception as a parameter to the constructor of the current exception object
*/
class Program
{
public static void Main()
{
try
{
try
{
Console.WriteLine("Enter the first number: ");
int firstNumber = Convert.ToInt32(Console.ReadLine());
//read the user input string, convert to an int, and store it in a variable, firstNumber
Console.WriteLine("Enter the second number: ");
int secondNumber = Convert.ToInt32(Console.ReadLine());
//read the user input string, convert to an int, and store it in a variable, secondNumber
int result = firstNumber/secondNumber;
Console.WriteLine("Result = {0}", result);
}
catch (Exception exception) //the first caught exception
{
string filePath = @"C:\SampleFiles\Log.txt";
if (File.Exists(filePath))
{
StreamWriter sw = new StreamWriter(filePath);
sw.Write(exception.GetType().Name + " - " + exception.Message); //write exception type and message to Log.txt
sw.Close();
Console.WriteLine("There was a problem. Check the Log.txt file.");
}
else
{
throw new FileNotFoundException(string.Format("{0} does not exist.", filePath), exception);
//this will retain the information from the original exception by passing in the 'exception' object as a parameter to the FileNotFoundException object
//in other words, the original exception is sent to the constructor of the current exception
}
}
}
catch (Exception exception) //the current caught exception
{
Console.WriteLine("Current Exception: {0} ", exception.GetType().Name);
if (exception.InnerException != null) //if the inner exception is null, don't print
{
Console.WriteLine("Inner Exception: : {0}", exception.InnerException.GetType().Name);
}
}
Console.ReadKey();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment