Java Java intro
  1. Java intro
  2. Java basics
Java core
  1. Java variables
  2. Java conditionals
  3. Java loops
  4. Java arrays
  5. Java strings
Object-oriented Java
  1. Java OOP 1
  2. Java OOP 2
  3. Java packages
  4. Java interfaces
Java interactive
  1. Java user input
  2. Java exceptions
  3. Java events
Graphical Java
  1. Java GUI
  2. Java GUI layout
  3. Java graphics
Java extras
  1. Java applets
  2. Java sounds
  3. Java random numbers
Java wrap-up
  1. Java summary

Java exceptions

Exceptions are used to handle situations where something unexpected might happen, such as attempting to divide by zero, a file you're trying to access is not found, and more.

This tutorial focuses on:

The various Java exceptions

Java has classes that can be used to handle exceptions in various situations.

NOTE: The base class of all the exception classes is the class Exception and it is located in the java.lang package.

The try-catch block

The way to deal with exceptions is to use a try-catch block. The try-catch block will execute one set of code if an exception does not occur, and a different set of code if an exception does occur. Specify within the try-catch block which exception it is you are watching for.

Syntax:
try{ code to execute if exception doesn't occur; } catch(anExceptionThatMayOccur){ code to execute if exception does occur; }
Example:
try{ name = reader.readLine(); System.out.println("Your name is " + name); } //watch for an input/output exception catch(IOException ioe){ System.out.println("An unexpected error has occured"); }

The try-catch-finally block

The try-catch-finally block is the same as the try-catch block with one addition. The try-catch-finally block contains a set of code that will execute whether an exception occured or not.

Syntax:
try{ code to execute if exception doesn't occur; } catch(anExceptionThatMayOccur){ code to execute if exception does occur; } finally{ code to execute whether exception occurs or not; }
Example:
try{ name = reader.readLine(); System.out.println("Your name is " + name); } //watch for an input/output exception catch(IOException ioe){ System.out.println("An unexpected error has occured"); } finally{ //print this whether an exception occurs or not System.out.println("Thanks for stopping by!); }
© Copyright 2013-2014 Landofcode.com
Terms of use | Privacy policy | Copyright information