-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathException_Handling.cs
52 lines (48 loc) · 1.46 KB
/
Exception_Handling.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
* Exception is any kind of error that disturbs the normal flow of the program.
* if exception occurs, then whole program is stopped.
* to deal with such error exception handling mechanism is required.
* it contains 4 keywords
*
* 1. try: use to surround a code that can cause error
* 2. catch: use to handle the error
* 3. throw: use to throw an exception
* 4. finally: this block will always execute whether exception occurs or not
*/
using System;
namespace Basics
{
class ExceptionHandling
{
private int x;
private int y;
public void SetData()
{
Console.WriteLine("Enter first number: ");
x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter second number: ");
y = Convert.ToInt32(Console.ReadLine());
}
public void Divide()
{
try
{
int div = this.x / this.y;
Console.WriteLine("Division: " + div);
}
catch (DivideByZeroException d)
{
Console.WriteLine($"Cannot divide {this.x} by {this.y}.\n {d}");
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
{
Console.WriteLine("This block will always execute whether exception occurs or not.");
}
Console.WriteLine("Out of try/catch block.");
}
}
}