1 / 46

Intermediate Java Exception Handling Guide

Learn how to handle errors in Java programs, understand exceptions, try-catch-finally blocks, and stream processing. Explore BufferedReader, PrintWriter, and building a simple expression evaluator.

awick
Download Presentation

Intermediate Java Exception Handling Guide

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Handling Errors • What happens if someone attempts to push an item into a stack that is full? • Many times it is the client that knows what the appropriate thing to do is in the case of an error. • Exceptions provide a method of informing a client that an error has occurred and provides a mechanism for handling the error cleanly. • Many languages provide support for exceptions. Intermediate Java

  2. Java Exception Handling • An exception occurs, thrown, when something goes wrong while a program is running. • If an exception is not handled, caught, the program will terminate. • When an exception is thrown, the exception is passed to the caller of the method. • The caller can then handle the exception or allow it to propagate back up the call chain. Intermediate Java

  3. Java Exceptions • An exception object stores information about the case of an exception and can be passed as a value to an exception handler. • All exception classes must be a direct or indirect subclass of class Throwable. • An exception class, despite its name, is an ordinary class defined in the normal way. Intermediate Java

  4. Exception Class Hierarchy Object serious errors that are typically non-recoverable these exceptions must be explicitly dealt with. Throwable Exception Error other classes ... other classes ... RunTimeException other classes ... Intermediate Java

  5. What Exceptions are Thrown? • How do you figure out what exception will be thrown that you must handle? • read the documentation for the class you are using • read the documentation about the various exception classes • I often simply use the methods I want and let the compiler tell me when I missed something!! • Example: FileReader Intermediate Java

  6. Try, Catch, and Finally • A try block is wrapped around code that may cause an exception. • catch blocks following the try block can contain code to deal with the exception. • A finally block contains code that will be executed whether or not an exception occurs. • In most cases try and catch blocks suffice Intermediate Java

  7. Syntax try { statementSequence } catch ( parameter ) { statementSequence } finally { statementSequence } Intermediate Java

  8. CmdLine public class CmdLine { public static void main( String args[] ) { for ( int i=0; i<args.length; i++ ) { int val; try { val = Integer.parseInt( args[i] ); System.out.println( val ); } catch ( NumberFormatException e ) { System.out.println( "??" ); } } } } Intermediate Java

  9. Streams • Java provides many stream classes that let you work with data in the forms that you usually use rather than at the low, byte level. • These are implemented in the abstract classes InputStream and Outputstream. • The methods in these classes provide the ability to do simple, byte oriented operations. Intermediate Java

  10. Streams and Files • Data files are handled using two abstractions: • the basic file abstraction is provided by the library class File. This encapsulates all the details of what a file is and how it is named. • The stream abstraction provides a way of reading and writing data to and from a file. • Reader streams deal with input and are subclasses of Reader, while writer streams perform output and are subclasses of Writer. Intermediate Java

  11. BufferedReader • A BufferedReader reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. • The buffer size may be specified, or the default size may be used. • A BufferedReader is usually wrapped around any Reader whose read() operations may be costly. Intermediate Java

  12. FileEcho import java.io.*; public class FileEcho { public static void main( String args[] ) { if ( args.length>0 ) { BufferedReader in = null; try { in = new BufferedReader( new FileReader( args[0] ) ); while ( in.ready() ) { char ch = (char)in.read(); System.out.print( ch ); } } catch ( FileNotFoundException e ) { System.out.println( "File not found" ); } catch( IOException e ) { System.out.println( "Read error" ); System.exit(1); }}}} Intermediate Java

  13. InputStreamReader • An InputStreamReader is a bridge from byte streams to character streams: it reads bytes and translates them into characters according to a specified character encoding. • Each invocation of one of an InputStreamReader's read() methods may cause one or more bytes to be read from the underlying byte-input stream. Intermediate Java

  14. PrintWriter • A PrintWriter prints formatted representations of objects to a text-output stream. • Flushing does not occur until the flush() method is invoked. It is possible to enable automatic flushing, which causes a flush to take place after any println() method is invoked. The output of a newline character does not cause a flush. • Methods in this class never throw I/O exceptions. Intermediate Java

  15. Building a Simple Expression Evaluator • Consider building an expression evaluator for the following: • identifiernumber; • identifier ; • The code to do this follows. It uses the following classes: • InputStreamReader • StreamTokenizer • HashTable Intermediate Java

  16. ExprEval import java.io.*; import java.util.*; public class ExprEval { public static void main( String args[] ) { StreamTokenizer lex = new StreamTokenizer( new InputStreamReader( System.in ) ); final int WANT_WORD = 0; final int WANT_NUM = 1; final int WANT_SEMI = 2; int curState = WANT_WORD; String curId = null; Hashtable symTbl = new Hashtable(); lex.ordinaryChar( '-' ); // '-' is treated normally lex.lowerCaseMode( true ); // make case insensitive Intermediate Java

  17. ExprEval try { while ( lex.nextToken() != StreamTokenizer.TT_EOF ) { switch ( lex.ttype ) { case lex.TT_WORD: if ( curState == WANT_WORD ) { curId = lex.sval; curState = WANT_NUM; } else curState = WANT_SEMI; break; case lex.TT_NUMBER: if ( curState == WANT_NUM ) symTbl.put( curId, new Integer( (int)lex.nval) ); curState = WANT_SEMI; break; case ';': if ( curState == WANT_NUM ) System.out.println( symTbl.get( curId ) ); curState = WANT_WORD; break; default: curState = WANT_SEMI; }}} catch( Exception e ) { System.out.println( "I/O Error" ); }}} Intermediate Java

  18. Classes • The class declaration introduces a new class. • A class describes the structure and behavior of its instance objects in terms of instance variables and methods. • Like variables, classes may be declared at different scopes. The scope of a class directly affects certain properties of the class. • We will start with top-level classes. Intermediate Java

  19. Class Syntax classmodifier identifier{ constructorDeclarations methodDeclarations staticMemberDeclarations instanceVariableDeclarations staticVariableDeclarations } Intermediate Java

  20. Class Modifiers • Top-level classes can optionally be declared as: • public • a public class is globally accessible. A single source file can have only one public class or interface. • abstract • an abstract class can have no instance objects. • final • a final class cannot be subclasses. • A class that does not have a modifier, can only be accessed by classes in the same package. Intermediate Java

  21. Public, Private and Protected • Any declaration at class scope can be proceeded by one of the following: • public • a declaration is accessible by any class • protected • a declaration is accessible to any subclass, or to any class in the same package. • private • a declaration is only accessible within the class it is declared in. Intermediate Java

  22. Instance Variables • Instance variables form the state of an instance object. • An instance variable can be declared as final, meaning that it is a constant. class Class1 { public String hello = “Hello”; public final String world = “World”; protected int count = 0; private float length = 2.345f; } Intermediate Java

  23. Methods • Class methods define the behavior of the object. They are where the control statements go. • A method name is an identifier. Following the method name is a parenthesized formal parameter list, which may be empty (the parenthesis are still required). • Each parameter consists of a type name followed by a parameter variable name. Intermediate Java

  24. Constructors • A constructor is a method that can be used to control initialization. • A constructor is declared like a method: • constructors have no return type • the constructor name is the same as the class • A constructor with an empty parameter list is known as a default constructor. • If a class does not define a constructor, the compiler will automatically insert one. Intermediate Java

  25. IntStack import java.util.*; public class IntStack { private Vector data; public IntStack() { data = new Vector(); }; public void push( int newValue ) { data.addElement( new Integer( newValue ) ); } public int top() { return ((Integer)data.lastElement()).intValue(); } public void pop() { data.removeElementAt( data.size()-1 ); } public boolean isEmpty() { return data.isEmpty(); } public boolean isFull() { return false; } } Intermediate Java

  26. this • this is a final variable that holds reference to the object in which it exists (i.e. this points to the current object) • The type of this is the reference type of the object • It is sometimes necessary to pass a reference to the current object as a parameter to another method. Intermediate Java

  27. StackNode public class StackNode { private Object data; private StackNode next, prev; public StackNode( Object o ) { this( o, null ); } public StackNode( Object o, StackNode n ) { data = o; next = n; } public StackNode getNext() { return next; } public Object getData() { return data; } } Intermediate Java

  28. LinkedStack public class LinkedStack { private StackNode tos = null; public boolean isEmpty() { return tos == null; } public boolean isFull() { return false; } public void push( Object o ) { tos = new StackNode( o, tos ); } public void pop() { tos = tos.getNext(); } public Object top() { return tos.getData(); } } Intermediate Java

  29. TestStack public class testStack { public static void main( String args[] ) { int i; LinkedStack stack=new LinkedStack(); for (i=0; i<10; i++) stack.push( new Integer( i ) ); while (!stack.isEmpty()) { System.out.println( stack.top() ); stack.pop(); } } } Intermediate Java

  30. Static or Class Variables • A static variable belongs to a class and is not part of the state of individual instance objects. • Only one copy of each static variable exists. • Class variables have several uses: • they are global to the class and can be shared by all objects of the class. • class constants (using final) • Static variables must be explicitly initialized (because no constructor can do it). Intermediate Java

  31. Elevator public class Elevator { private static int nextId = 0; public final static int UP = 0; public final static int DOWN = 1; private int direction = UP; private int myId; public Elevator() { myId = nextId++; } public int getId() { return myId; } public int getDirection() { return direction; } public void setDirection( int dir ) { switch ( dir ) { case UP: case DOWN: direction = dir; }}} Intermediate Java

  32. TestElevator public class TestElevator { public static void main( String args[] ) { Elevator a = new Elevator(); Elevator b = new Elevator(); Elevator c = new Elevator(); a.setDirection( a.DOWN ); b.setDirection( Elevator.DOWN ); System.out.println( "Elevator A: Id=" + a.getId() + ", Dir=" + a.getDirection() ); System.out.println( "Elevator B: Id=" + b.getId() + ", Dir=" + b.getDirection() ); System.out.println( "Elevator C: Id=" + c.getId() + ", Dir=" + c.getDirection() ); } } Intermediate Java

  33. Static Methods • Static methods generally follow the same rules as methods: • a static method belongs to a class not its instance objects. • a static method can be called both directly and for an object of the same class • a static method cannot access any instance variables or methods (since it does not belong to an instance object) • this cannot be used Intermediate Java

  34. Static Methods • There is one special use of static methods in the form of static main. • When a class defines a public static method main, it provides a starting point for execution of a program using that class. • Any class can have a static main method. • Static methods are generally used to provide utility or helper methods. For examples see java.lang.Math. Intermediate Java

  35. Packages • A package allows a collection of classes to be grouped together into a single named unit which also acts as a scope. • A package is declared using a package statement (must be the first statement in a source file) • packagepackageName; • Packages are imported using an import statement • importpackageName.className; • importpackageName.* ; Intermediate Java

  36. Packages • It is also possible to specify the name of a zip file in the CLASSPATH as well as directories containing class files. • Any class from another package must be imported. for all Java classes this must be done explicitly with the exception of java.lang. • If a class is not defined as part of a package, then it is considered to be part of the unnamed default package. Intermediate Java

  37. Mapping Packages to Files • Package names map to directory names. Each directory contains all the .class files for a given package • mcc.examples.stack would map to mcc\examples\stack • the relative pathname is then appended to each entry in the CLASSPATH variable to create a full pathname • Check this out: • edu.rit.cs.ptt.classes.mcc.examples Intermediate Java

  38. Inner Classes • Inner, or Nested, classes are standard classes declared within the scope of a standard top-level class. • There are different kinds of inner class • nested top-level class • member class • local class • anonymous class Intermediate Java

  39. Nested Top-Level Classes class outer { private static class NestedTopLevel { normal class stuff } normal class stuff } • Nested top-level classes are declared as static within a standard top-level class (sort of like a standard class member). • They follow the same rules as standard classes • private static classes cannot be seen the enclosing class • public static allows the class to be seen outside Intermediate Java

  40. LinkedStack2 public class LinkedStack2 { private StackNode tos = null; private static class StackNode { private Object data; private StackNode next, prev; public StackNode( Object o ) { this( o, null ); } public StackNode( Object o, StackNode n ) { data = o; next = n; } public StackNode getNext() { return next; } public Object getData() { return data; } } public boolean isEmpty() { return tos == null; } public boolean isFull() { return false; } public void push( Object o ) { tos = new StackNode( o, tos ); } public void pop() { tos = tos.getNext(); } public Object top() { return tos.getData(); } } Intermediate Java

  41. Member Classes • A member class is a nested top-level class that is not declared static. • This means the member class has a this reference which refers to the enclosing class object. • Member classes cannot declare static variables, methods or nested top-level classes. • Member objects are used to create data structures that need to know about the object they are contained in. Intermediate Java

  42. Class5 class Class5 { private class Member { public void test() { i = i + 10; System.out.println( i ); System.out.println( s ); } } public void test() { Member n = new Member(); n.test(); } private int i = 10; private String “Hello”; } Intermediate Java

  43. this Revisited • To support member classes several extra kinds of expressions are provided • x = this.y is valid only if y is an instance variable declared by the member class, not if y belongs to the enclosing class. • x = TestClass.this.y allows access to y that belongs to the enclosing class. • Inner classes can be nested to any depth and the this mechanism can be used with nesting. Intermediate Java

  44. new Revisited • Member class objects can only be created if they have access to an enclosing class object. • This happens by default if the member class object is created by an instance method belonging to its enclosing class. • Otherwise it is possible to specify an enclosing class object using the new operator as follows • B b = a.new B(); Intermediate Java

  45. Local Classes • A local class is a class declared within the scope of a compound statement, like a local variable. • Local classes follow the member class syntax but cannot include static variables, methods or classes. In additional they cannot be declared public, protected, private or static. • A local class has the ability to access final variables and parameters in the enclosing scope. • Handy in the AWT. Intermediate Java

  46. Anonymous Classes • An anonymous class is a local class that does not have a name. • An anonymous class allows an object to be created using an expression that combines object creation with the declaration of the class. • This avoids naming a class, at the cost of only ever being able to create one instance of that anonymous class. • Again this is handy in the AWT. Intermediate Java

More Related