CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Exceptions

Exceptions handling
Exceptions
Try statement

How to use the try statement

  • You use the catch clause of the try statement to catch specific exception types.
  • You should code the catch clauses in sequence from the most specific class in the Throwable hierarchy to the least specific class.
  • A finally clause is executed whether or not an exception is thrown.

The syntax of the try statement

try
{
    // statements that can cause an exception to be thrown
}
catch (MostSpecificExceptionType e)
{
    // statements that handle the exception
}
catch (LeastSpecificExceptionType e)
{
    // statements that handle the exception
}
finally
{
    // statements that are executed whether or not
    // an exception is thrown
}

Code that uses a try statement in a loop to validate user input

Scanner sc = new Scanner(System.in);

// get the file name from the user
RandomAccessFile file;
String fileName;
boolean validFileName = false;
while (!validFileName)
{
    System.out.print("File name: ");
    fileName = sc.next();
    try
    {
        file = new RandomAccessFile(fileName, "r");
        validFileName = true;
    }
    catch (FileNotFoundException e)
    {
        System.out.println("File not found.");
    }
    catch (IOException e)
    {
        System.out.println("An I/O error occurred.");
    }
    sc.nextLine();
}
System.out.println("File name accepted.");
Previous | Try statement | Finally clause | Throws clause | Throw statement | Throwable class | Next