C# try Statements and Exceptions
In this chapter you will learn:
- What are C# try Statements and Exceptions
- Syntax for try statement
- Example for try statement
- Use a nested try block
Description
A try
statement specifies a code block subject to error-handling or cleanup code.
The try
block must be followed by a catch block, a finally block, or both.
The catch
block executes when an error occurs in the try block.
The finally
block performs cleanup code, whether or not an error occurred.
Syntax
A try statement looks like this:
try//w w w . ja v a 2 s . c o m
{
... // exception may get thrown within execution of this block
}
catch (ExceptionA ex)
{
... // handle exception of type ExceptionA
}
catch (ExceptionB ex)
{
... // handle exception of type ExceptionB
}
finally
{
... // cleanup code
}
Example
Consider the following program. Because x is zero, the runtime throws a DivideByZeroException, and our program terminates. We can prevent this by catching the exception as follows:
using System;/* w ww . ja v a 2 s. c o m*/
class Test
{
static int Calc (int x) { return 10 / x; }
static void Main()
{
try
{
int y = Calc (0);
Console.WriteLine (y);
}
catch (DivideByZeroException ex)
{
Console.WriteLine ("x cannot be zero");
}
Console.WriteLine ("program completed");
}
}
The code above generates the following result.
Example 2
using System; /*from w w w .ja v a 2 s .c o m*/
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:
- What is catch clause
- Example catch statement
- Catch general exception type
- Use multiple catch statements
- Use the 'catch all' catch statement
C# Exception
C# Exception classes
C# finally Block
C# throw statement
C# System Exception
C# Exception classes
C# try Statements and Exceptions
C# catch ClauseC# finally Block
C# throw statement
C# System Exception