JAVA THEORY B SCH COMPUTER SCIENCE II SEM

JAVA THEORY B. SC(H) COMPUTER SCIENCE II SEM

THROWS § The java throws keyword is used to declare an exception in method. § A throws clause lists the types of exceptions that a method might throw § This is necessary for all exceptions, except those of type error or Runtime. Exception. § All other exceptions that a method can throw must be declared in the throws clause. • Syntax: type method-name(parameter-list) throws exceptions-list { //body of method }

EXAMPLE • class Throws. Demo { • static void throw. One() throws Illegal. Access. Exception { • System. out. println("Inside throw. One. "); • throw new Illegal. Access. Exception("demo"); • } • public static void main(String args[]) { • try { • throw. One(); • } catch (Illegal. Access. Exception e) { • System. out. println("Caught " + e); } } } • output : inside throw. One • caught java. lang. Illegal. Access. Exception: demo

FINALLY • finally creates a block of code that will be executed after a try /catch block has completed and before the code following the try/catch block. • The finally block will execute whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement matches the exception. • Any time a method is about to return to the caller from inside a try/catch block, via an uncaught exception or an explicit return statement, the finally clause is also executed just before the method returns. • This can be useful for closing file handles and freeing up any other resources that might have been allocated at the beginning of a method with the intent of disposing of them before returning. The finally clause is optional. However, each try statement requires at least one catch or a finally clause.

EXAMPLE • class Finally. Demo { static void proc. A() { try { System. out. println("inside proc. A"); throw new Runtime. Exception("demo"); } finally { System. out. println("proc. A's finally"); } } static void proc. B() { try { System. out. println("inside proc. B"); return; } finally { System. out. println("proc. B's finally"); } } static void proc. C() { try { System. out. println("inside proc. C"); } finally { System. out. println("proc. C's finally"); } } public static void main(String args[]) { try { proc. A(); } catch (Exception e) { System. out. println("Exception caught"); } proc. B(); proc. C(); } }

OUTPUT • inside proc. A's finally Exception caught inside proc. B's finally inside proc. C's finally

CHAINED EXCEPTIONS • The chained exception feature allows you to associate another exception with an exception. • This second exception describes the cause of the first exception. For example, imagine a situation in which a method throws an Arithmetic. Exception because of an attempt to divide by zero. • However, the actual cause of the problem was that an I/O error occurred, which caused the divisor to be set improperly. Although the method must certainly throw an Arithmetic. Exception, since that is the error that occurred, you might also want to let the calling code know that the underlying cause was an I/O error.

CONT… • To allow chained exceptions, two constructors and two methods were added to Throwable. The constructors are shown here: Throwable(Throwable cause. Exc) Throwable(String msg, Throwable cause. Exc) • The chained exception methods supported by Throwable are get. Cause( ) and init. Cause( ). Throwable get. Cause( ) Throwable init. Cause(Throwable cause. Exc)

CONTD… • The get. Cause( ) method returns the exception that underlies the current exception. If there is no underlying exception, null is returned. • The init. Cause( ) method associates cause. Exc with the invoking exception and returns a reference to the exception.
![EXAMPLE • class Chain. Exc. Demo { • public static void main(String args[]) { EXAMPLE • class Chain. Exc. Demo { • public static void main(String args[]) {](http://slidetodoc.com/presentation_image_h2/7c6591cf481168028968e0b67e490d6b/image-10.jpg)
EXAMPLE • class Chain. Exc. Demo { • public static void main(String args[]) { static void demoproc() { try { // create an exception Null. Pointer. Exception e = new Null. Pointer. Exception("top layer"); demoproc(); // add a cause e. init. Cause(new Arithmetic. Exception("cause")); throw e; } } catch(Null. Pointer. Exception e) { // display top level exception System. out. println("Caught: " + e); // display cause exception System. out. println("Original cause: " + e. get. Cause()); } } }

OUTPUT • Caught: java. lang. Null. Pointer. Exception: top layer Original cause: java. lang. Arithmetic. Exception: cause

CHAPTER -13 I/O , TRY-WITH-RESOURCES AND OTHER TOPICS

STREAMS • A stream is an abstraction that either produces or consumes information. • A stream is linked to a physical device by the Java I/O system. All streams behave in the same manner, even if the actual physical devices to which they are linked differ. • Streams are a clean way to deal with input/ output without having every part of your code understand the difference between a keyboard and a network, for example. Java implements streams within class hierarchies defined in the java. io package. • Java defines two types of streams: byte and character. Byte streams provide a convenient means for handling input and output of bytes. Byte streams are used, for example, when reading or writing binary data. Character streams provide a convenient means for handling input and output of characters. They use Unicode and, therefore, can be internationalized. Also, in some cases, character streams are more efficient than byte streams.

BYTE STREAM CLASSES AND CHARACTER STREAM CLASSES • Byte streams are defined by using two class hierarchies. At the top are two abstract classes: Input. Stream and Output. Stream. • To use the stream classes, you must import java. io. stream class name. • The abstract classes Input. Stream and Output. Stream define several key methods that the other stream classes implement. Two of the most important are read( ) and write( ), which, respectively, read and write bytes of data. • Character streams are defined by using two class hierarchies. At the top are two abstract classes: Reader and Writer. • The abstract classes Reader and Writer define several key methods that the other stream classes implement. Two of the most important methods are read( ) and write( ), which read and write characters of data

THE PREDEFINED STREAMS • System also contains three predefined stream variables: in, out, and err. These fields are declared as public, static, and final within System. • This means that they can be used by any other part of your program and without reference to a specific System object. System. out refers to the standard output stream. By default, this is the console. System. in refers to standard input, which is the keyboard by default. • System. in is an object of type Input. Stream; System. out and System. err are objects of type Print. Stream.

READING CONSOLE INPUT • In Java, console input is accomplished by reading from System. in. To obtain a characterbased stream that is attached to the console, wrap System. in in a Buffered. Reader object. Buffered. Reader supports a buffered input stream. A commonly used constructor is shown here: Buffered. Reader(Reader input. Reader) Here, input. Reader is the stream that is linked to the instance of Buffered. Reader that is being created. Reader is an abstract class. One of its concrete subclasses is Input. Stream. Reader, which converts bytes to characters. To obtain an Input. Stream. Reader object that is linked to System. in, use the following constructor: Input. Stream. Reader(Input. Stream input. Stream) Buffered. Reader br = new Buffered. Reader(new Input. Stream. Reader(System. in));

READING CHARACTERS • To read a character from a Buffered. Reader, use read( ). The version of read( ) that we will be using is int read( ) throws IOException • Each time that read( ) is called, it reads a character from the input stream and returns it as an integer value. It returns – 1 when the end of the stream is encountered. As you can see, it can throw an IOException

EXAMPLE • import java. io. *; OUTPUT: class BRRead { Enter characters, 'q' to quit. public static void main(String args[]) throws IOException { char c; 123 abcq Buffered. Reader br = new Buffered. Reader(new Input. Stream. Reader(System. in)); 1 System. out. println("Enter characters, 'q' to quit. "); // read characters do { c = (char) br. read(); System. out. println(c); } while(c != 'q'); } } 2 3 a b c q

READING STRINGS • To read a string from the keyboard, use the version of read. Line( ) that is a member of the Buffered. Reader class. Its general form is shown here: String read. Line( ) throws IOException As you can see, it returns a String object. The following program demonstrates Buffered. Reader and the read. Line( ) method; the program reads and displays lines of text until you enter the word "stop":

EXAMPLE: • import java. io. *; class BRRead. Lines { public static void main(String args[]) throws IOException { // create a Buffered. Reader using System. in Buffered. Reader br = new Buffered. Reader(new Input. Stream. Reader(System. in)); String str; System. out. println("Enter lines of text. "); System. out. println("Enter 'stop' to quit. "); do { str = br. read. Line(); System. out. println(str); } while(!str. equals("stop")); } }
- Slides: 20