catch exceptions
In this chapter you will learn:
Use multiple catch statements
using System; //from ja v a 2 s . c om
class MainClass {
public static void Main() {
int[] numer = { 4, 8, 16};
int j=0;
for(int i=0; i < 10; i++) {
try {
Console.WriteLine(numer[i] + " / " +
numer[i] + " is " +
numer[i]/j);
}
catch (DivideByZeroException) {
// catch the exception
Console.WriteLine("Can't divide by Zero!");
}
catch (IndexOutOfRangeException) {
// catch the exception
Console.WriteLine("No matching element found.");
}
}
}
}
The code above generates the following result.
Use the 'catch all' catch statement
using System; //ja v a 2 s . com
class MainClass {
public static void Main() {
int[] numer = { 4, 8};
int d = 0;
for(int i=0; i < 10; i++) {
try {
Console.WriteLine(numer[i] + " / " +
numer[i] + " is " +
numer[i]/d);
}
catch {
Console.WriteLine("Some exception occurred.");
}
}
}
}
The code above generates the following result.
Some exception occurred./* ja v a 2s . c om*/
Some exception occurred.
Some exception occurred.
Some exception occurred.
Some exception occurred.
Some exception occurred.
Some exception occurred.
Some exception occurred.
Some exception occurred.
Some exception occurred.
Next chapter...
What you will learn in the next chapter:
- What is finally block in exception handling
- finally is always executed
- Dispose a StreamWriter in finally block
Home » C# Tutorial » Exception