Academic Tutorials



English | French | Portugese | German | Italian
Home Advertise Payments Recommended Websites Interview Questions FAQs
News Source Codes E-Books Downloads Jobs Web Hosting
Chats

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
CSS 1.0
CSS 2.0
HLML
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
DHTML Tutorial
HTML DOM Tutorial
WMLScript Tutorial
E4X Tutorial
Server Scripting
ASP Tutorial
PERL Tutorial
SQL Tutorial
ADO Tutorial
CVS
Python
Apple Script
PL/SQL Tutorial
SQL Server
PHP
.NET (dotnet)
Microsoft.Net
ASP.Net
.Net Mobile
C# : C Sharp
ADO.NET
VB.NET
VC++
Multimedia
SVG Tutorial
Flash Tutorial
Media Tutorial
SMIL Tutorial
Photoshop Tutorial
Gimp Tutorial
Matlab
Gnuplot Programming
GIF Animation Tutorial
Scientific Visualization Tutorial
Graphics
Web Building
Web Browsers
Web Hosting
W3C Tutorial
Web Building
Web Quality
Web Semantic
Web Careers
Weblogic Tutorial
SEO
Web Site Hosting
Domain Name
Java Tutorials
Java Tutorial
JSP Tutorial
Servlets Tutorial
Struts Tutorial
EJB Tutorial
JMS Tutorial
JMX Tutorial
Eclipse
J2ME
JBOSS
Programming Langauges
C Tutorial
C++ Tutorial
Visual Basic Tutorial
Data Structures Using C
Cobol
Assembly Language
Mainframe
Forth Programming
Lisp Programming
Pascal
Delphi
Fortran
OOPs
Data Warehousing
CGI Programming
Emacs Tutorial
Gnome
ILU
Soft Skills
Communication Skills
Time Management
Project Management
Team Work
Leadership Skills
Corporate Communication
Negotiation Skills
Database Tutorials
Oracle
MySQL
Operating System
BSD
Symbian
Unix
Internet
IP-Masquerading
IPC
MIDI
Software Testing
Testing
Firewalls
SAP Module
ERP
ABAP
Business Warehousing
SAP Basis
Material Management
Sales & Distribution
Human Resource
Netweaver
Customer Relationship Management
Production and Planning
Networking Programming
Corba Tutorial
Networking Tutorial
Microsoft Office
Microsoft Word
Microsoft Outlook
Microsoft PowerPoint
Microsoft Publisher
Microsoft Excel
Microsoft Front Page
Microsoft InfoPath
Microsoft Access
Accounting
Financial Accounting
Managerial Accounting
Network Sites


Errors and Exceptions in Java


Previoushome 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,

A D V E R T I S E M E N T
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());
}



Be the first one to comment on this page.




  Java Tutorial eBooks
More Links » »
 
 Java Tutorial FAQs
More Links » »
 
 Java Tutorial Interview Questions
More Links » »
 
 Java Tutorial Articles
More Links » »
 
 Java Tutorial News
More Links » »
 
 Java Tutorial Jobs
More Links » »

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

Previoushome Next

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

HTML Quizzes
HTML Quiz
XHTML Quiz
CSS Quiz
TCP/IP Quiz
CSS 1.0 Quiz
CSS 2.0 Quiz
HLML Quiz
XML Quizzes
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 Quizzes
JavaScript Quiz
VBScript Quiz
DHTML Quiz
HTML DOM Quiz
WMLScript Quiz
E4X Quiz
Server Scripting Quizzes
ASP Quiz
PERL Quiz
SQL Quiz
ADO Quiz
CVS Quiz
Python Quiz
Apple Script Quiz
PL/SQL Quiz
SQL Server Quiz
PHP Quiz
.NET (dotnet) Quizzes
Microsoft.Net Quiz
ASP.Net Quiz
.Net Mobile Quiz
C# : C Sharp Quiz
ADO.NET Quiz
VB.NET Quiz
VC++ Quiz
Multimedia Quizzes
SVG Quiz
Flash Quiz
Media Quiz
SMIL Quiz
Photoshop Quiz
Gimp Quiz
Matlab Quiz
Gnuplot Programming Quiz
GIF Animation Quiz
Scientific Visualization Quiz
Graphics Quiz
Web Building Quizzes
Web Browsers Quiz
Web Hosting Quiz
W3C Quiz
Web Building Quiz
Web Quality Quiz
Web Semantic Quiz
Web Careers Quiz
Weblogic Quiz
SEO Quiz
Web Site Hosting Quiz
Domain Name Quiz
Java Quizzes
Java Quiz
JSP Quiz
Servlets Quiz
Struts Quiz
EJB Quiz
JMS Quiz
JMX Quiz
Eclipse Quiz
J2ME Quiz
JBOSS Quiz
Programming Langauges Quizzes
C Quiz
C++ Quiz
Visual Basic Quiz
Data Structures Using C Quiz
Cobol Quiz
Assembly Language Quiz
Mainframe Quiz
Forth Programming Quiz
Lisp Programming Quiz
Pascal Quiz
Delphi Quiz
Fortran Quiz
OOPs Quiz
Data Warehousing Quiz
CGI Programming Quiz
Emacs Quiz
Gnome Quiz
ILU Quiz
Soft Skills Quizzes
Communication Skills Quiz
Time Management Quiz
Project Management Quiz
Team Work Quiz
Leadership Skills Quiz
Corporate Communication Quiz
Negotiation Skills Quiz
Database Quizzes
Oracle Quiz
MySQL Quiz
Operating System Quizzes
BSD Quiz
Symbian Quiz
Unix Quiz
Internet Quiz
IP-Masquerading Quiz
IPC Quiz
MIDI Quiz
Software Testing Quizzes
Testing Quiz
Firewalls Quiz
SAP Module Quizzes
ERP Quiz
ABAP Quiz
Business Warehousing Quiz
SAP Basis Quiz
Material Management Quiz
Sales & Distribution Quiz
Human Resource Quiz
Netweaver Quiz
Customer Relationship Management Quiz
Production and Planning Quiz
Networking Programming Quizzes
Corba Quiz
Networking Quiz
Microsoft Office Quizzes
Microsoft Word Quiz
Microsoft Outlook Quiz
Microsoft PowerPoint Quiz
Microsoft Publisher Quiz
Microsoft Excel Quiz
Microsoft Front Page Quiz
Microsoft InfoPath Quiz
Microsoft Access Quiz
Accounting Quizzes
Financial Accounting Quiz
Managerial Accounting Quiz
Testimonials | Contact Us | Link to Us | Site Map
Copyright ? 2008. Academic Tutorials.com. All rights reserved Privacy Policies | About Us
Our Portals : Academic Tutorials | Best eBooksworld | Beyond Stats | City Details | Interview Questions | Discussions World | Excellent Mobiles | Free Bangalore | Give Me The Code | Gog Logo | Indian Free Ads | Jobs Assist | New Interview Questions | One Stop FAQs | One Stop GATE | One Stop GRE | One Stop IAS | One Stop MBA | One Stop SAP | One Stop Testing | Webhosting in India | Dedicated Server in India | Sirf Dosti | Source Codes World | Tasty Food | Tech Archive | Testing Interview Questions | Tests World | The Galz | Top Masala | Vyom | Vyom eBooks | Vyom International | Vyom Links | Vyoms | Vyom World | Important Websites
Copyright ? 2003-2024 Vyom Technosoft Pvt. Ltd., All Rights Reserved.