Welcome To - MaCHAcK

JAVA TUTORIAL FOR BEGINNERS PART-5

Author: P.R.O.V.I.D.E.R. // Category:
JAVA TUTORIAL FOR BEGNIRES PART-5!!!!!!!!!!!!!!!!!!!

PART-5

* Catching Exceptions
* File I/O and Streams
* How to make executable jar files in JDK1.3.1?


"Catching Exceptions"

An exception is a point in the code where something out of the ordinary has happened and the regular flow of the program needs to be interrupted; an exception is not necessarily an error. A method which has run into such a case will throw an exception using the throw(ExceptionClass) method. When an exception is thrown it must be caught by a catch statement that should sit right after a try statement.

// This is the Hello program in Java
class Hello {

public static void main (String args[]) {

/* Now let's say hello */
System.out.print("Hello ");
System.out.println(args[0]);
}

}
If you run the program without giving it any command line arguments, then the runtime system generates an exception something like,

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException at Hello.main(C:\javahtml\Hello.java:7)

Since we didn't give Hello any command line arguments there wasn't anything in args[0]. Therefore Java kicked back this not too friendly error message about an "ArrayIndexOutOfBoundsException."

we can fix this problem by testing the length of the array before we try to access its first element (using array.length). This works well in this simple case, but this is far from the only such potential problem.

What is an Exception ?

Let us see what happens when an exception occurs and is not handled properly

When you compile and run the following program

public class Test{
public static void main(String str[]){
int y = 0;
int x = 1;
// a division by 0 occurs here.
int z = x/y;
System.out.println("after didvision");
}
}

The execution of the Test stops and this is caused by the division by zero at - x/y - an exception has been thrown but has not been handled properly.

How to handle an Exception ?

To handle an Exception, enclose the code that is likely to throw an exception in a try block and follow it immediately by a catch clause as follows

public class Test{
public static void main(String str[]){
int y = 0;
int x = 1;
// try block to "SEE" if an exception occurs
try{
int z = x/y;
System.out.println("after didvision");
// catch clause below handles the
// ArithmeticException generated by
// the division by zero.
} catch (ArithmeticException ae)
{System.out.println(" attempt to divide by 0");}
System.out.println(" after catch ");
}
}

The output of the above program is as follows

attempt to divide by 0
after catch

the statement - System.out.println("after didvision") - is NOT executed, once an exception is thrown, the program control moves out of the try block into the catch block.

The goal of exception handling is to be able to define the regular flow of the program in part of the code without worrying about all the special cases. Then, in a separate block of code, you cover the exceptional cases. This produces more legible code since you don't need to interrupt the flow of the algorithm to check and respond to every possible strange condition. The runtime environment is responsible for moving from the regular program flow to the exception handlers when an exceptional condition arises.

In practice what you do is write blocks of code that may generate exceptions inside try-catch blocks. You try the statements that generate the exceptions. Within your try block you are free to act as if nothing has or can go wrong. Then, within one or more catch blocks, you write the program logic that deals with all the special cases.

To start a section of code which might fail or not follow through you start a try clause:

try
{
// Section of code which might fail
}

The try statement is needed in case of an exception. If the read fails in some way it will throw an exception of type java.io.IOException. That exception must be caught in this method, or the method can declare that it will continue throwing that message. Exception handling is a very powerful tool, you can use it to catch and throw exceptions and thus group all your error handling code very well and make it much more readable in larger more complex applications. After the try section there must exist one or more catch statements to catch some or all of the exceptions that can happen within the try block. Exceptions that are not caught will be passed up to the next level, such as the function that called the one which threw the exception, and so on. .

try
{
// Section of code which might fail
}
catch (Exception1ThatCanHappen E)
{
// things to do if this exception was thrown..
}
catch (Exception2ThatCanHappen E)
{
// things to do if this exception was thrown..
}

Here's an example of exception handling in Java using the Hello World program above:

Source Code

// This is the Hello program in Java
class ExceptionalHello {

public static void main (String args[]) {

/* Now let's say hello */
try {
System.out.println("Hello " + args[0]);
}
catch (Exception e) {
System.out.println("Hello whoever you are");
}
}

}

You may or may not print an error message. If you write an exception handler and you don't expect it to be called, then by all means put a

System.out.println("Error: " + e);

This has the folowing advantages over handling your errors internally:

* You can react to an error in custom defined way. A read error does not mean that the program should crash.
* You can write code with no worry about failure which will be handled by the users of your class.
* You can group your error handling code much better.
* You can make your application more transactional focused with nested try catch blocks:

A simple Java code which demonstrates the exception handling in Java

Refer to the java API document to see all exception types that can be handled in Java.

Source Code

public class excep2
{
public static void main(String args[])
{
int i =0 ;
//Declare an array of strings
String Box [] = {"Book", "Pen", "Pencil"};
while(i<4)
{
try
{
System.out.println(Box);

}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Subscript Problem " + e);
i++;
}
finally
{
System.out.println("This is always printed.");
}
i++;
}
}
}

__________________________________________________________________________________________________________

" File I/O and Streams"

You can write data to a file instead of the computer screen. You can write certain data to a file while still putting other data on the screen. Or you may need access to multiple files simultaneously. Or you may want to query the user for input rather than accepting it all on the command line. Or maybe you want to read data out of a file that's in a particular format. In Java all these methods take place as streams. < > Using File I/O streams. The System.out.println() statement we've been using all along is an implementation of Streams.

A program that writes a string to a file

In order to use the Java file classes, we must import the Java input/output package (java.io) in the following manner

import java.io.*;

Inside the main method of our program, we must declare a FileOutputStream object. In this case, we wish to write a string to the file, and so we create a new PrintStream object that takes as its constructor the existing FileOutputStream. Any data we send from PrintStream will now be passed to the FileOutputStream, and ultimately to disk. We then make a call to the println method, passing it a string, and then close the connection.

Source Code

/*
* FileOutput
* Demonstration of FileOutputStream and PrintStream classes
*/

import java.io.*;

class FileOutput
{

public static void main(String args[])
{
FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object

try
{
// Create a new file output stream connected to "myfile.txt"
out = new FileOutputStream("myfile.txt");

// Connect print stream to the output stream
p = new PrintStream( out );

p.println ("This is written to a file myFile.txt");

p.close();
}
catch (Exception e)
{
System.err.println ("Error writing to the file myFile.txt");
}
}
}

Interactively communicating with the user
Program asking the user for their name and then prints a personalized greeting.

Source Code

import java.io.*;

class PersonalHello {

public static void main (String args[])
{

byte name[] = new byte[100];
int nr_read = 0;

System.out.println("Your name Please?");
try {
nr_read = System.in.read(name);
System.out.print("Hello ");
System.out.write(name,0,nr_read);
}
catch (IOException e) {
System.out.print("I did not get your name.");
}

}

}
In code that does any significant input or output you'll want to begin by importing all the various java.io classes. import.java.io.*; Most of the reading and writing you do in Java will be done with bytes. Here we've started with an array of bytes that will hold the user's name.

First we print a query requesting the user's name. Then we read the user's name using the System.in.read() method. This method takes a byte array as an argument, and places whatever the user types in that byte array. Then, like before, we print "Hello." Finally we print the user's name.

The program doesn't actually see what the user types until he or she types a carriage return. This gives the user the chance to backspace over and delete any mistakes. Once the return key is pressed, everything in the line is placed in the array.

Reading Numbers
Often strings aren't enough. A lot of times you'll want to ask the user for a number as input. All user input comes in as strings so we need to convert the string into a number.

The getNextInteger() method that will accept an integer from the user. Here it is:

static int getNextInteger() {

String line;

DataInputStream in = new DataInputStream(System.in);
try {
line = in.readLine();
int i = Integer.valueOf(line).intValue();
return i;
}
catch (Exception e) {
return -1;
}

} // getNextInteger ends here

Reading Formatted Data
It's often the case that you want to read not just one number but multiple numbers. Sometimes you may need to read text and numbers on the same line. For this purpose Java provides the StreamTokenizer class.

Writing a text file
Sometimes you want to save your output in a file. To do this we'll need to learn how to write data to a file.

Source Code

// Write the Fahrenheit to Celsius table in a file

import java.io.*;

class FahrToCelsius {

public static void main (String args[]) {

double fahr, celsius;
double lower, upper, step;

lower = 0.0; // lower limit of temperature table
upper = 300.0; // upper limit of temperature table
step = 20.0; // step size

fahr = lower;

try {

FileOutputStream fout = new FileOutputStream("test.out");

// now to the FileOutputStream into a PrintStream
PrintStream myOutput = new PrintStream(fout);

while (fahr <= upper) { // while loop begins here
celsius = 5.0 * (fahr-32.0) / 9.0;
myOutput.println(fahr + " " + celsius);
fahr = fahr + step;
} // while loop ends here

} // try ends here
catch (IOException e) {
System.out.println("Error: " + e);
System.exit(1);
}

} // main ends here

}
There are only three things necessary to write formatted output to a file rather than to the standard output:

1. Open a FileOutputStream using a line like

FileOutputStream fout = new FileOutputStream("test.out");
This line initializes the FileOutputStream with the name of the file you want to write into.
2. Convert the FileOutputStream into a PrintStream using a statement like

PrintStream myOutput = new PrintStream(fout);

The PrintStream is passed the FileOutputStream from step 1.
3. Instead of using System.out.println() use myOutput.println(). System.out and myOutput are just different instances of the PrintStream class. To print to a different PrintStream we keep the syntax the same but change the name of the PrintStream.

Reading a text file
Now that we know how to write a text file, let's try reading one. The following code accepts a series of file names on the command line and then prints those filenames to the standard output in the order they were listed.

// Imitate the Unix cat utility

import java.io.*;

class cat {

public static void main (String args[]) {

String thisLine;

//Loop across the arguments
for (int i=0; i < args.length; i++) {

//Open the file for reading
try {
FileInputStream fin = new FileInputStream(args);

// now turn the FileInputStream into a DataInputStream
try {
DataInputStream myInput = new DataInputStream(fin);

try {
while ((thisLine = myInput.readLine()) != null) { // while loop begins here
System.out.println(thisLine);
} // while loop ends here
}
catch (Exception e) {
System.out.println("Error: " + e);
}
} // end try
catch (Exception e) {
System.out.println("Error: " + e);
}

} // end try
catch (Exception e) {
System.out.println("failed to open file " + args);
System.out.println("Error: " + e);
}
} // for end here

} // main ends here

}

______________________________________________________________________________________________

"How to make executable jar files in JDK1.3.1?"

Instructions for creating an Executable .jar file

Make or modify the Manifest.MF to YourManifest.MF.

1) YourClassNameWithMain is the class name (case sensitive) without .class extension
2) No extra spaces following the YourClassName withMain.

Manifest-Version:1.0
Main-Class: YourClassNameWithMain
Created-by:1.2(Sun Microsystems Inc.)
On Command line : type the following
jar cvfm YourJarFileName.jar YourManifest.MF*

or

jar cvfm YourJarFileName.jar YourManifest.MF -C classes yourClassPath
Drag-drop the YourJarFileName.jar to your desktop double click it, it runs
If your program only has System.out.println ("whatever"); statements, it will
display nothing. The same will happen when you run it useing java at command line

You need some windows code to see it run

Instructions for creating a .jar file. jar utility comes with your JDK1.2.2 It compresses your file similar to zip utility, and more Java.

You can use it on any machine installed JDK

Create a folder name it anything
Make that folder your current directory
put all your files for turning in (do not put any extra) in that directory.

Be sure to put your html file, if there is one
At your dos prompt, while you are in the directory that you created , type in:
jar cvf Prj02.jar*

This will take ALL the files in the directory including subdirectories and place them in a .jar file Prj02 that can be replaced by any of your desired jar file name.

To test it, you can extract the contents of jar file by typing:
jar xvf Prj02.jar

0 Responses to "JAVA TUTORIAL FOR BEGINNERS PART-5"

Post a Comment