09/03/2010
Exception
- compile time error
- run time error
exception handling: how to handle exception
- try
- catch
- finally
- throw
Divide by Zero exception
1/0 = ∞
→System error
public static void Main()
{
Console.WriteLine("Please enter a number.");
string num = Console.ReadLine();
try
{
int i = int.Parse(num); // If user put in alphabet, it won't work. →Guard for future
int j = 5 / i; //If user put in 0, it won't work. →Guard for future
Console.WriteLine("Result" + j);
}
catch
{
Console.WriteLine("Don't allow to put in 0.");
}
}
Real industry
System
|
Exception (class) : Using inheritance
___|___________________
| | | | ………
Divide X y z
byZero
try
{
int j=5/0
}
catch(DevidebyZero s)
{ ---------------- ---
classname variable name
}
catch(Exception e)
{
}
- In case of divide by zero, exception is caught by catch divide by class.
- In other case, exception is caught by catch exception class.
Pros.
Program don't stop.
It will be shown meaningful message.
- try
----------------1 | ○ | ○ |
----------------2 | ○ | ○ |
try
{
----------------3 | ○ | ○ |
----------------4 | ○ | × |
}
catch
{
----------------5 |
| ○ |
----------------6 |
| ○ |
}
finally
{
---------------7 | ○ | ○ |
---------------8 | ○ | ○ |
}
---------------9 | ○ | ○ |
*Finally block is always executed.
Option
- try & catch
- try & finally
- try & catch & finally
throw
try
{
throw new Exception(); //using to throw an exception programmatically.
}
static memory: int i=5;
dynamic memory: file
0 件のコメント:
コメントを投稿