finally
In this chapter you will learn:
- What is finally block in exception handling
- finally is always executed
- Dispose a StreamWriter in finally block
What is finally block in exception handling
Sometimes you can define a block of code that will execute when a try/catch block is left. The general form of a try/catch that includes finally is shown here:
try {// j a v 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 {
// finally code
}
The finally block will be executed whenever execution leaves a try/catch block.
using System; /*from jav a2 s .c om*/
class MainClass {
public static void Main() {
Console.WriteLine("Receiving ");
try {
int i=1, j=0;
i = i/j;
}
catch (DivideByZeroException) {
Console.WriteLine("Can't divide by Zero!");
return;
}
catch (IndexOutOfRangeException) {
Console.WriteLine("No matching element found.");
}
finally {
Console.WriteLine("Leaving try.");
}
}
}
The code above generates the following result.
Receiving
Can't divide by Zero!
Leaving try.
finally is always executed
finally
block is always executed
even if an exception was thrown in the try.
using System;/* j a v a 2 s.c om*/
using System.IO;
class Processor
{
public void ProcessFile()
{
FileStream f = new FileStream("wrongNameFile.txt", FileMode.Open);
try
{
StreamReader t = new StreamReader(f);
string line;
while ((line = t.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
finally
{
f.Close();
}
}
}
class Test
{
public static void Main()
{
Processor processor = new Processor();
try
{
processor.ProcessFile();
}
catch (Exception e)
{
Console.WriteLine("Exception: {0}", e);
}
}
}
The code above generates the following result.
Dispose a StreamWriter
using System;//j ava 2 s . c o m
using System.IO;
public sealed class MainClass
{
static void Main(){
StreamWriter sw = new StreamWriter("Output.txt");
try {
sw.WriteLine( "This is a test of the emergency dispose mechanism" );
}
finally {
if( sw != null ) {
((IDisposable)sw).Dispose();
}
}
}
}
Next chapter...
What you will learn in the next chapter:
- Throwing an exception
- throw DivideByZeroException
- Rethrow an exception
- Throw Exception in finally statement