290 likes | 309 Views
Learn how to handle errors and exceptions in Java programming efficiently using try-catch blocks and streams for improved error management and code reliability.
E N D
Handling Errors • What happens if someone attempts to add an item to a queue 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. Exceptions and Streams
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. Exceptions and Streams
Java Exceptions • An exception object stores information about the cause of an exception. Exceptions must be a subclass of Throwable • Throwable and its subclasses have two constructors, one that takes no arguments, and one that takes a String argument that can be used to produce an error message • A Throwable class contains a snapshot of the state of the program at the time it was created • It can also contain a message string that gives more information about the error Exceptions and Streams
Exception Class Hierarchy indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions Object these exceptions must be explicitly dealt with Throwable Exception Error other classes ... other classes ... RunTimeException These exceptions do not need to be caught or declared in throws clause other classes ... Exceptions and Streams
ActivationException ApplicationException AWTException ClassNotFoundException, DataFormatException GeneralSecurityException IllegalAccessException InstantiationException InterruptedException IOException NoSuchMethodException ParseException ArithmeticException ArrayIndexOutOfBoundsException ArrayStoreException ClassCastException ClassNotFoundException IllegalAccessException IllegalArgumentException IndexOutOfBoundsException NegativeArraySizeException NullPointerException NumberFormatException ... Java Exceptions (partial list) Exceptions and Streams
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!! Exceptions and Streams
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 Exceptions and Streams
Syntax try { statementSequence } catch ( parameter ) { statementSequence } finally { statementSequence } Exceptions and Streams
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( "??" ); } } } } Exceptions and Streams
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. Exceptions and Streams
throws • If a method wishes to pass an exception to a caller, the exception must be listed in the throws clause of the method • public int aMethod() throws NumberFormatException • If a method does something that may cause an exception to be thrown • the exception must be caught • or the exception must be listed in the method’s throw clause Exceptions and Streams
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. Exceptions and Streams
Streams • To receive information, a program opens a stream and reads the information: • A program can send information by opening a stream to a destination and writes the information: Exceptions and Streams
Using Streams • No matter where the information is coming from or going to and no matter what type of data is being read or written, the algorithms for reading and writing data is pretty much always the same Reading open a stream while more information read information close the stream Writing open a stream while more information write information close the stream Exceptions and Streams
java.io.* • The java.io package contains a collection of stream classes that support reading/writing from/to streams • Streams are divided into two class hierarchies based on the type of data on which they operate. Exceptions and Streams
InputStream Classes InputStream ByteArray InputStream File InputStream Filter InputStream Piped InputStream Sequence InputStream StringBuffer InputStream Object InputStream Buffered InputStream Checked InputStream Data InputStream Digest InputStream Inflator InputStream ProgressMonitor InputStream PushBack InputStream GZip InputStream Zip InputStream Exceptions and Streams
Data Sink Streams Exceptions and Streams
Data Processing Streams Exceptions and Streams
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 text input and are subclasses of Reader, writer streams perform text output and are subclasses of Writer. Exceptions and Streams
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. Exceptions and Streams
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); }}}} Exceptions and Streams
InputEcho import java.io.*; public class InputEcho { public static void main( String args[] ) { // Set things up to read from the keyboard BufferedReader keyboard = new BufferedReader( new InputStreamReader( System.in ) ); // Read stuff form input and dump to output try { String inString; while ( ( inString = keyboard.readLine() ) != null ) { System.out.println( inString ); } } catch ( IOException e ) { System.err.println( "InputEcho: I/O error" ); System.exit( 1 ); } } } Exceptions and Streams
ReadNums import java.util.*; import java.io.*; public class ReadNums { public static void main( String args[] ) { // Make sure the number of arguments is correct if ( args.length != 1 ) { System.err.println( "Usage: ReadNums sourceFile" ); System.exit(1); } // Initialize src since the assignment is done inside a try block BufferedReader src = null; // Attempt to open the file for reading try { src = new BufferedReader( new FileReader( args[0] ) ); } catch ( FileNotFoundException e ) { System.err.println( "ReadNums: Unable to open source file" ); System.exit(1); } Exceptions and Streams
ReadNums (continued) // Read the numbers a line at a time from the source file Vector data = new Vector(); try { String line; while ( ( line = src.readLine() ) != null ) { try { int num = Integer.parseInt( line ); data.addElement( new Integer( num ) ); } catch ( NumberFormatException e ) {} } src.close(); } catch ( IOException e ) { System.err.println( "ReadNums: " + e.getMessage() ); System.exit(1); } // Print out the results for ( int i=0; i<data.size(); i++ ) System.out.println( data.elementAt( i ) ); }} Exceptions and Streams
InputStreamReader • An InputStreamReaderis 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. Exceptions and Streams
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. Exceptions and Streams
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 Exceptions and Streams
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 Exceptions and Streams
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" ); }}} Exceptions and Streams