Academic Tutorials



English | French | Portugese | German | Italian
Google

Home Source Codes E-Books Downloads Contact Us About Us

Java Tutorial
Java Introduction
Object Oriented Programming Concepts
Anatomy of a Java Application
Syntax and Semantics of Java
Java Objects, Classes, and Interfaces
The String and StringBuffer Classes in Java
Setting Program Attributes in Java
Using System Resources in Java
Threads of Control in Java
Errors and Exceptions in Java
Java Input and Output Streams
Overview of Java Applet
Creating an Applet User Interface in Java
Communicating with Other Programs in Java
Overview of the Java UI
Using GUI Building Blocks in Java
Laying Out Components within a Container
Working with Graphics in Java
How Java Differs from C and C++
Java Summary

HTML Tutorials
HTML Tutorial
XHTML Tutorial
CSS Tutorial
TCP/IP Tutorial
XML Tutorials
XML Tutorial
XSL Tutorial
XSLT Tutorial
DTD Tutorial
Schema Tutorial
XForms Tutorial
XSL-FO Tutorial
XML DOM Tutorial
XLink Tutorial
XQuery Tutorial
XPath Tutorial
XPointer Tutorial
RDF Tutorial
SOAP Tutorial
WSDL Tutorial
RSS Tutorial
WAP Tutorial
Web Services Tutorial
Browser Scripting
JavaScript Tutorial
VBScript Tutorial
AJAX Tutorial
DHTML Tutorial
HTML DOM Tutorial
WMLScript Tutorial
E4X Tutorial
Server Scripting
ASP Tutorial
PHP Tutorial
PERL Tutorial
SQL Tutorial
ADO Tutorial
.NET (dotnet)
Microsoft.Net
XML Web Services
ASP.Net
.Net Mobile
C# : C Sharp
ADO.NET
VB.NET
Multimedia
SVG Tutorial
Flash Tutorial
Media Tutorial
SMIL Tutorial
Web Building
Web Browsers
Web Hosting
W3C Tutorial
Web Building
Web Quality
Web Semantic
Web Careers
Java Tutorials
Java Tutorial
JSP Tutorial
Servlets Tutorial
Struts Tutorial
EJB Tutorial
JMS Tutorial
JMX Tutorial
Programming Langauges
C Tutorial
C++ Tutorial
Visual Basic Tutorial
Data Structures Using C
Soft Skills
Communication Skills
Time Management
Project Management
Team Work
Leadership Skills
Corporate Communication
Negotiation Skills


Errors and Exceptions in Java

Previous Next



The Java language make use exceptions to provide the error handling capabilities for all its programs. Here you will learn what does an exception mean, how to throw and catch the exceptions, what to do with the exception once you have caught it, and how to make best use of the exception class hierarchy provided by Java development environment.




What is an Exception?

Definition: An exception is an event which occurs during execution of the program which disrupts the normal flow of the instructions. Different types of errors can cause exceptions: problems which range from serious hardware errors, such as hard disk crash, to the simple programming errors, like trying to access the out-of-bounds array element. When such error occurs within a Java method, the method will create an exception object and hands it to the runtime system. The exception object do contains the information about exception including its type and state of the program when error occurred. Runtime system is then responsible to find some code to handle error. In the Java terminology, creating exception object and handing it to runtime system is called "throwing an exception".




Hotjava's Catch or Declare Requirement
import java.io.*;
import java.util.Vector;

class ListOfNumbers
{
private Vector victor;
final int size = 10;

public ListOfNumbers ()
{
int i;
victor = new Vector(size);
for (i = 0; i < size; i++)
victor.addElement(new Integer(i));
}
public void writeList()
{
PrintStream pStr = null;

System.err.println("Entering try statement");
int i;
pStr = new PrintStream(
new BufferedOutputStream(
new FileOutputStream("OutFile.txt")));

for (i = 0; i < size; i++)
pStr.println("Value at: " + i + " = " + victor.elementAt(i));

pStr.close();
}
}

The example above defines and implements the class called "ListOfNumbers". Upon construction, the ListOfNumbers class creates a Vector which contains ten Integer elements with sequential values 0 through 9. ListOfNumbers class also defines the method "writeList()" that writes the list of numbers into the text file "OutFile.txt". The writeList() method calls up two more methods that can throw exceptions.

First,

pStr = new PrintStream(new BufferedOutputStream(new FileOutputStream("OutFile.txt")));

This line invokes the constructor for FileOutputStream which throws an IOException when the file cannot be opened for any of the reason.

Second, the Vector class's elementAt() method

pStr.println("Value at: " + i + " = " + victor.elementAt(i));

This method will throw ArrayIndexOutOfBoundsException if you pass an index whose value is very small (negative number) or very large (larger than number of elements contained by the Vector currently).

If you try to compile ListOfNumbers class, the compiler prints the error message about an exception thrown by FileOutputStream constructor, but it will not display the error message about an exception thrown by elementAt(). This is because the exception thrown by the FileOutputStream constructor, IOException, is non-runtime exception and the exception thrown by elementAt() method, ArrayIndexOutOfBoundsException, is the runtime exception. Java requires only to catch or declare non-runtime exceptions.




Catch and Handle an Exception

The first step for constructing an exception handler is to enclose statements that might throw exception within the try block. In general, try block looks something like this:

try
{
Java statements
}

The segment "Java statements" in the code above consists one or more legal Java statements which could potentially throw an exception. To construct the exception handler for writeList() method from ListOfNumbers class, we need to enclose the exception-throwing statements of writeList() method within the try block. There are more than one ways to accomplish this task: we can put each statement which may potentially throw the exception within its own try statement, and provide the separate exception handlers for each of the try. Or you can put all the writeList() statements within the single try statement and associate multiple handlers to it. The following example uses single try statement for the entire method as the code tends to be easier to read.

PrintStream pstr;
try
{
int i;

System.err.println("Entering try statement");
pStr = new PrintStream(
new BufferedOutputStream(
new FileOutputStream("OutFile.txt")));

for (i = 0; i < size; i++)
pStr.println("Value at: " + i + " = " + victor.elementAt(i));
}

The try statement governs the statements enclosed within it and it defines the scope of any exceptions handlers (which are established by subsequent catch blocks) associated with it. In other words, if an exception does occurs within the try statement, then that exception is handled by some appropriate exception handler which is associated with this try statement.




The catch Block(s)

As studied before, the try statement defines the scope of the associated exception handlers. We do associate exception handlers with a try statement by providing one or more of the sequential catch blocks directly after a try block.

try
{
. . .
} catch ( . . . )
{
. . .
} catch ( . . . )
{
. . .
} . . .

There can be no intervening code between the end of try statement and the beginning of first catch statement. The general form of catch statement is:

catch (SomeThrowableClassName variableName)
{
Java statements
}

Catch statement governs series of legal Java statements. These statements are executed when the exception handler is invoked. The runtime system invokes exception handler when a exception whose type matches with that of catch statement's argument is thrown within handler's try block.

The writeList() method from ListOfNumbers class uses two exception handlers for the try statement, one handler for each of the two types of exceptions which can be thrown within a try block, ArrayIndexOutOfBoundsException and IOException.

try
{
. . .
} catch (ArrayIndexOutOfBoundsException e)
{
System.err.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage()); } catch (IOException e)
{
System.err.println("Caught IOException: " + e.getMessage());
}




Share And Enjoy:These icons link to social bookmarking sites where readers can share and discover new web pages.
  • blinkbits
  • BlinkList
  • blogmarks
  • co.mments
  • connotea
  • del.icio.us
  • De.lirio.us
  • digg
  • Fark
  • feedmelinks
  • Furl
  • LinkaGoGo
  • Ma.gnolia
  • NewsVine
  • Netvouz
  • RawSugar
  • Reddit
  • scuttle
  • Shadows
  • Simpy
  • Smarking
  • Spurl
  • TailRank
  • Wists
  • YahooMyWeb

Previous Next

Keywords: unchecked exceptions, exception classes, exception handling, exception class


HTML Quizes
HTML Quiz
XHTML Quiz
CSS Quiz
TCP/IP Quiz
XML Quizes
XML Quiz
XSL Quiz
XSLT Quiz
DTD Quiz
Schema Quiz
XForms Quiz
XSL-FO Quiz
XML DOM Quiz
XLink Quiz
XQuery Quiz
XPath Quiz
XPointer Quiz
RDF Quiz
SOAP Quiz
WSDL Quiz
RSS Quiz
WAP Quiz
Web Services Quiz
Browser Scripting Quizes
JavaScript Quiz
VBScript Quiz
AJAX Quiz
DHTML Quiz
HTML DOM Quiz
WMLScript Quiz
E4X Quiz
Server Scripting Quizes
ASP Quiz
PHP Quiz
PERL Quiz
SQL Quiz
ADO Quiz
.NET (dotnet) Quizes
Microsoft.Net Quiz
XML Web Services Quiz
ASP.Net Quiz
.Net Mobile Quiz
C# : C Sharp Quiz
ADO.NET Quiz
VB.NET Quiz
Multimedia Quizes
SVG Quiz
Flash Quiz
Media Quiz
SMIL Quiz
Web Building  Quizes
Web Browsers Quiz
Web Hosting Quiz
W3C Quiz
Web Building Quiz
Web Quality Quiz
Web Semantic Quiz
Web Careers Quiz
Java Quizes
Java Quiz
JSP Quiz
Servlets Quiz
Struts Quiz
EJB Quiz
JMS Quiz
JMX Quiz
Programming Langauges Quizes
C Quiz
C++ Quiz
Visual Basic Quiz
Data Structures Using C Quiz
Soft Skills Quizes
Communication Skills Quiz
Time Management Quiz
Project Management Quiz
Team Work Quiz
Leadership Skills Quiz
Corporate Communication Quiz
Negotiation Skills Quiz

Privacy Policy
Copyright © 2003-2008 Vyom Technosoft Pvt. Ltd., All Rights Reserved.