try...catch
In this chapter you will learn:
Statements to handle exceptions
C# exception handling is managed via four keywords: try, catch, throw, and finally.
try {//j av a 2 s . c o m
// block of code to monitor for errors
}
catch (ExcepType1 exOb) {
// handler for ExcepType1
}
catch (ExcepType2 exOb) {
// handler for ExcepType2
}
.
.
finally{
}
If no exception is thrown by a try block, no catch statements will be executed and program control resumes after the catch statement.
Exception handling with trying and catching
using System;/*from ja v a 2 s . co m*/
class MainClass{
public static void Main(){
Console.WriteLine("Before catch");
int Zero = 0;
try {
int j = 22 / Zero;
} catch (Exception e) {
Console.WriteLine("Exception " + e.Message);
}
Console.WriteLine("After catch");
}
}
The code above generates the following result.
Use a nested try block
using System; /*from j a v a2 s.com*/
class MainClass {
public static void Main() {
int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 };
int d = 0;
try { // outer try
for(int i=0; i < 10; i++) {
try { // nested try
Console.WriteLine(numer[i] + " / " +
numer[i] + " is " +
numer[i]/d);
}
catch (DivideByZeroException) {
// catch the exception
Console.WriteLine("Can't divide by Zero!");
}
}
}
catch (IndexOutOfRangeException) {
// catch the exception
Console.WriteLine("No matching element found.");
Console.WriteLine("Fatal error -- program terminated.");
}
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter: