Code Snippets

  

Java Source Code


Welcome to Dream.In.Code
Getting Java Help is Easy!

Join 105,765 Java Programmers for FREE! Ask your question and get quick answers from experts. There are 1,579 online right now! We've got more than 500 tutorials and 2,000 snippets. Join and find out why Dream.In.Code is the #1 programming help community on the internet! Registration is fast and FREE... Join Now!




Try... Catch... Finally

in simple code, or Exceptions that need not be thrown, Try/Catch/Finally blocks can come in handy

Submitted By: William_Wilson
Actions:
Rating:
Views: 2,580

Language: Java

Last Modified: May 5, 2006
Instructions: Try is the code which MAY generate an error.
Catch is the code to run upon an error in the Try block.
Finally is run no matter what after the Try block upon completion or after the Catch block in the case of an error.

A full class Exceptions is provided as an example of all 3 blocks.

Snippet


  1. public class Exceptions{
  2.      public static void main(String args[]){
  3.           try{
  4.                System.out.println("Try Block before the error.");
  5.                System.out.println(1/0);
  6.                System.out.println("Try Block after the error."); //this line will not print
  7.           }
  8.           catch(java.lang.ArithmeticException e){
  9.                System.out.println("Catch Block");
  10.                System.out.println("A Stack Trace of the Error:");
  11.                e.printStackTrace();
  12.                //e.getMessage(); //This one is useable when we write our own exceptions
  13.                System.out.println("The operation is not possible.");
  14.           }
  15.           finally{
  16.                System.out.println("Finally Block");
  17.           }
  18.      }
  19. }

Copy & Paste


Comments


herefishyfishy 2008-05-06 14:12:26

Don't forget: If the program exits or the program return;s from the method where the try...catch...finally is, the finally block will not run!


Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month