C# catch Clause
In this chapter you will learn:
- What is catch clause
- Example catch statement
- Catch general exception type
- Use multiple catch statements
- Use the 'catch all' catch statement
Description
A catch clause specifies what type of exception to catch.
Example
The type must either be System.Exception or a subclass of System.Exception. Catching System.Exception catches all possible errors. You also catch specific exception types.
You can handle multiple exception types with multiple catch clauses:
using System;/*from ww w . j a v a 2s . co m*/
class Test
{
static void Main (string[] args)
{
try
{
byte b = byte.Parse (args[0]);
Console.WriteLine (b);
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine ("Please provide at least one argument");
}
catch (FormatException ex)
{
Console.WriteLine ("That's not a number!");
}
catch (OverflowException ex)
{
Console.WriteLine ("You've given me more than a byte!");
}
}
}
The code above generates the following result.
Catch general exception type
An exception can be caught without specifying a variable if you don't need to access its properties:
catch (StackOverflowException) // no variable
{
...
}
Furthermore, you can omit both the variable and the type (meaning that all exceptions will be caught):
catch { ... }
Example 2
using System; /*from w ww.ja v a 2s. c o m*/
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.
Example 3
using System; /*ww w. j a v a 2s.co m*/
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.
Next chapter...
What you will learn in the next chapter:
- What is finally Block
- How to use finally block in exception handling
- Example for finally Block
- finally is always executed
- Dispose a StreamWriter in finally block