Exceptions:
1. Create a situation where an exception will occur
2. Create a situation where an exception will occur, and catch the exception.
3. Create a situation where an exception will occur, and catch the exception, the display a custom message.
4. Create a situation where an exception will occur, and catch the exception, then display the caught exception’s internal message.
5. Write code utilize the finally block
6. Create a situation where an exception will occur, and pass the exception to be handled up the chain.
7. Create a situation where no exception will occur, but generate an exception anyway.
static void Main(string[] args)
{
//1. Create a situation where an exception will occur
int x = 5, y = 0;
//System.DivideByZeroException here
double z = x / y;
Console.ReadLine();
}
static void Main(string[] args)
{
//2. Create a situation where an exception will occur, and catch the exception.
try
{
int x = 5, y = 0;
//System.DivideByZeroException here
double z = x / y;
}
catch
{
}
Console.ReadLine();
}
static void Main(string[] args)
{
//3. Create a situation where an exception will occur, and catch the exception, the display a custom message.
try
{
int x = 5, y = 0;
//System.DivideByZeroException here
double z = x / y;
}
catch
{
Console.WriteLine("Exception! My custom message!");
}
Console.ReadLine();
}
static void Main(string[] args)
{
//4. Create a situation where an exception will occur, and catch the exception, then display the caught exception’s internal message.
try
{
int x = 5, y = 0;
//System.DivideByZeroException here
double z = x / y;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
static void Main(string[] args)
{
//5. Write code utilize the finally block
int x = 5, y = 0;
try
{
//System.DivideByZeroException here
double z = x / y;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
double z = x;
}
Console.ReadLine();
}
static void Main(string[] args)
{
//6. Create a situation where an exception will occur, and pass the exception to be handled up the chain.
int x = 5, y = 0;
try
{
double z = Div(x, y);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
public static double Div(double x, double y)
{
double z;
try
{
z = x / y;
}
catch (Exception)
{
throw;
}
finally
{
z = x;
}
return z;
}
static void Main(string[] args)
{
//7. Create a situation where no exception will occur, but generate an exception anyway.
int x = 5, y = 1;
try
{
double z = Div(x, y);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
public static double Div(double x, double y)
{
double z;
try
{
z = x / y;
}
catch (Exception)
{
throw;
}
finally
{
z = x;
}
throw new Exception("My exception!");
}
Comments
Leave a comment