Sie sind auf Seite 1von 17

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:
y y y y

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[i]); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Subscript Problem " + e); i++; } finally { System.out.println("This is always printed."); } i++; } } }

Methods (Includes Recursive Methods) A method is a group of instructions that is given a name and can be called up at any point in a program simply by quoting that name. Each calculation part of a program is called a method. Methods are logically the same as C's functions, Pascal's procedures and functions, and Fortran's functions and subroutines. When I wrote System.out.println("Hello World!"); in the first program we were using the System.out.println() method. The System.out.println() method actually requires quite a lot of code, but it is all stored for us in the System libraries. Thus rather than including that code every time we need to print, we just call the System.out.println() method. You can write and call your own methods too. Methods begin with a declaration. This can include three to five parts. First is an optional access specifier which can be public, private or protected. A public method can be called from pretty much anywhere. A private method can only be used within the class where it is defined. A protected method can be used anywhere within the package in which it is defined. Methods that aren't specifically declared public or private are protected by default. access specifier. We then decide whether the method is or is not static. Static methods have only one instance per class rather than one instance per object. All objects of the same class share a single copy of a static method. By default methods are not static. We finally specify the return type. Next is the name of the method. Source Code
class FactorialTest { //calculates the factorial of that number.

public static void main(String args[]) { int n; int i; long result; for (i=1; i <=10; i++) { result = factorial(i); System.out.println(result); } } // main ends here static long factorial (int n) { int i; long result=1; for (i=1; i <= n; i++) {

result *= i; } return result; } // factorial ends here

Recursive Methods Recursion is used when a problem can be reduced into one or several problems of the same nature, but a smaller size. This process is usually repeated until a boundary situation is reached, where the problem can be directly solved. Java supports recursive methods, i.e. even if you're already inside methodA() you can call methodA(). Example (A Recursive Counterpart of the Above Factorial Method) n! is defined as n times n-1 times n-2 times n-3 ... times 2 times 1 where n is a positive integer. 0! is defined as 1. As you see n! = n time (n-1)!. This lends itself to recursive calculation, as in the following method:
public static long factorial (int n) { if (n < 0) { return -1; } else if (n == 0) { return 1; } else { return n*factorial(n-1); } }

Classes and Objects Following the principles of Object Oriented Programming (OOP), everything in Java is either a class, a part of a class, or describes how a class behaves. Objects are the physical instantiations of classes. They are living entities within a program that have independent lifecycles and that are created according to the class that describes them. Just as many buildings can be built from one blueprint, many objects can be instantiated from one class. Many objects of different classes can be created, used, and destroyed in the course of executing a program. Programming languages provide a number of simple data types like int, float and String. However very often the data you want to work with may not be simple ints, floats or Strings. Classes let programmers define their own more complicated data types. All the action in Java programs takes place inside class blocks, in this case the HelloWorld class. In Java almost everything of interest is either a class itself or belongs to a class. Methods are defined inside the classes they belong to. Even basic data primitives like integers often need to be incorporated into classes before you can do many useful things with them. The class is the fundamental unit of Java programs. For instance consider the following Java program:
class HelloWorld { public static void main (String args[]) { System.out.println("Hello World"); } } class GoodbyeWorld { public static void main (String args[]) { System.out.println("Goodbye Cruel World!"); } }

Save this code in a single file called hellogoodbye.java in your javahtml directory, and compile it with the command javac hellogoodbye.java. Then list the contents of the directory. You will see that the compiler has produced two separate class files, HelloWorld.class and GoodbyeWorld.class. javac hellogoodbye.java The second class is a completely independent program. Type java GoodbyeWorld and then type java HelloWorld. These programs run and execute independently of each other although they exist in the same source code file.

Class Syntax Use the following syntax to declare a class in Java: //Contents of SomeClassName.java [ public ] [ ( abstract | final ) ] class SomeClassName [ extends SomeParentClass ] [ implements SomeInterfaces ] { // variables and methods are declared within the curly braces } * A class can have public or default (no modifier) visibility. * It can be either abstract, final or concrete (no modifier). * It must have the class keyword, and class must be followed by a legal identifier. * It may optionally extend one parent class. By default, it will extend java.lang.Object. * It may optionally implement any number of comma-separated interfaces. * The class's variables and methods are declared within a set of curly braces '{}'. * Each .java source file may contain only one public class. A source file may contain any number of default visible classes. * Finally, the source file name must match the public class name and it must have a .java suffix. Here is an example of a Horse class. Horse is a subclass of Mammal, and it implements the Hoofed interface. public class Horse extends Mammal implements Hoofed { //Horse's variables and methods go here } Lets take one more example of Why use Classes and Objects. For instance let's suppose your program needs to keep a database of web sites. For each site you have a name, a URL, and a description.
class website { String name; String url; String description; }

These variables (name, url and description) are called the members of the class. They tell you what a class is and what its properties are. They are the nouns of the class. members. A class defines what an object is, but it is not itself an object. An object is a specific instance of a class. Thus when we create a new object we say we are instantiating the object. Each class exists only once in a program, but there can be many thousands of objects that are instances of that class. To instantiate an object in Java we use the new operator. Here's how we'd create a new web site:

website x = new website();

Once we've got a website we want to know something about it. To get at the member variables of the website we can use the . operator. Website has three member variables, name, url and description, so x has three member variables as well, x.name, x.url and x.description. We can use these just like we'd use any other String variables. For instance:
website x = new website(); x.name = "freehavaguide.com"; x.url = "http://www.freejavaguide.com"; x.description = "A Java Programming Website"; System.out.println(x.name + " at " + x.url + " is " + x.description); 1

JAVA Tutorial - Class Declaration


A simple Java class declaration with constructor declaration: class simple { // Constructor simple(){ p = 1; q = 2; r = 3; } int p,q,r; } In class declaration, you can declare methods of the class: class simple { // Constructor simple(){ p = 1; q = 2; r = 3; } int p,q,r; public int addNumbers(int var1, int var2, int var3) { return var1 + var2 + var3; } public void displayMessage() { System.out.println("Display Message"); } } To invoke the class, you can create the new instance of the class: // To create a new instance class

Simple sim = new Simple(); // To access the methods of the class sim.addNumbers(5,1,2) // To show the result of the addNumbers System.out.println("The result is " + Integer.toString(addNumbers(5,1,2))); The complete listing of class declaration: class simple { // Constructor simple(){ p = 1; q = 2; r = 3; } int p,q,r; public int addNumbers(int var1, int var2, int var3) { return var1 + var2 + var3; } public void displayMessage() { System.out.println("Display Message"); } } class example1{ public static void main(String args[]) { // To create a new instance class Simple sim = new Simple(); // To show the result of the addNumbers System.out.println("The result is " + Integer.toString(addNumbers(5,1,2))); // To display message sim.displayMessage(); } }

Interfaces There is one thing in Java source code that is neither a class nor a member of a class. That's an interface. An interface defines methods that a class implements. In other words it declares what certain classes do. However an interface itself does nothing. All the action at least, happens inside classes. A class may implement one or more interfaces. This means that the class

subscribes to the promises made by those interfaces. Since an interface promises certain methods, a class implementing that interface will need to provide the methods specified by the interface. The methods of an interface are abstract -- they have no bodies. Generally, a class implementing an interface will not only match the method specifications of the interface, it will also provide bodies -- implementations -- for its methods.

For example, a ScoreCounter class might meet the contract specified by the Counting interface: interface Counting { abstract void increment(); abstract int getValue(); } So might a Stopwatch, although it might have a totally different internal representation. Both would have increment() and getValue() methods, but the bodies of these methods might look quite different. For example, a ScoreCounter for a basketball game might implement increment() so that it counts by 2 points each time, while a Stopwatch might call its own increment() method even if no one else does. A class that implements a particular interface must declare this explicitly: class ScoreCounter implements Counting { .... } If a class implements an interface, an instance of that class can also be treated as though its type were that interface. For example, it can be labeled with a name whose declared type is that interface. For example, an instance of class ScoreCounter can be labeled with a name of type Counting. It will also answer true when asked whether it's an instanceof that interface type: if myScoreCounter is a ScoreCounter, then myScoreCounter instanceof Counting is true. Similarly, you can pass or return a ScoreCounter whenever a Counting is required by a method signature. The generality of interfaces and the inclusion of multiple implementations within a single (interface) type is an extremely powerful feature. For example, you can use a name of type Counting to label either an instance of ScoreCOunter or an instance of Stopwatch (and use its increment() and getValue() methods) without even knowing which one you've got.

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[i]); // 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[i]); System.out.println("Error: " + e); } } // for end here

} // main ends here }

Das könnte Ihnen auch gefallen