Chat LIVE With Programming Experts! There Are 23 Online Right Now...

 

Code Snippets

  

Java Source Code


Welcome to Dream.In.Code
Become a Java Expert!

Join 244,283 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,132 people online right now. 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: 3,138

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!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month