Academic Java    Java Tutorial  >  Exceptions  >  try/catch

try/catch Example

Java try/catch EXAMPLE output An exception is an unusual condition during program execution.

When an exception occurs the flow of control is transferred to a special section of code where it is dealt with.

We say that the exception is 'thrown' to this section of code, which 'catches' it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// try/catch exception example
import java.io.*;

class TryCatchExceptionExample {

   public static void main(String[] args) {

      try {

         BufferedReader r = new BufferedReader(new FileReader("toto.txt"));

         int c=0;
         while((c=r.read())!=-1)   {System.out.print((char)c);}

         r.close();

      }
      catch (Exception e){
         System.out.println("*** an exception has been thrown");
      }

      System.out.println("bye");
   }
}

2-24 The program aims to open a file, read it character by character, and output each character in the process.

8-20 The try statement wraps a block of code called the try block. If an exception is thrown in the try block then control passes to the catch clause.
The catch clause contains code that handles the exception.

10-15 This is the try block. Notice that the code lies within braces {}.
Also notice that there are no statements between the try block and the catch clause.
An attempt is made to open a file. The attempt to open the file fails. An exception is thrown and control passes to the catch clause.

18-20 The catch clause acts like a method. The parameter is an instance of the class Exception which holds information about the thrown exception (which we do not use in this program).
The body of the catch clause lies within braces {} and is executed because the exception was thrown. Details of the exception are output. When the catch clause concludes, control passes to the next statement.

22 The statement following the catch clause is executed.

* try/catch Examples