Thursday 17 August 2017

EXCEPTION HANDLING




·         A Java exception is an object that describes an exceptional condition that has occurred in a piece of code. When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error. That method may choose to handle the exception itself or pass it on. Either way at some point, the exception is caught and processed.
·         Exceptions can be generated by the Java run time system or they can be manually generated by your code. Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment.
·         Manually generated exceptions are typically used to report some error condition to the caller of a method.
·         Java exception handling is managed via five keywords: try, catch, throw, throws and finally.
·         Program statements that you want to monitor for exceptions are contained within a try block. If an exception occurs within the try block, it is thrown. Your code can catch this exception using catch and handle it in some rational manner. System generated exceptions are automatically thrown by the Java run time system. To manually throw an exception use the keywords throw. Any exception that is thrown out of a method must be specified as such by a throws clause. Any code that absolutely must be executed before a method returns is put in a finally block.
·         All exception types are sub classes of the built in class Throwable. Thus Throwable is at the top of the exception class hierarchy. Immediately below Throwable are two sub classes that partition exceptions into two distinct branches. One branch is headed by Exception. This class is used for exceptional conditions that user programs should catch.
·         There is another important sub class of Exception called RuntimeException. Exceptions of this type are automatically defined for the programs that you write and include things such as division by zero and invalid array indexing.
·         To guard against and handle a run time error, simply enclose the code that you want to monitor inside a try block. Immediately following the try block, include a catch clause that specifies the exception type that you wish to catch. A try and its catch statement form a unit. The scope of the catch clause is restricted to those statements specified by the immediately preceding try statement. A catch statement cannot an exception thrown by another try statement.
·         The goal of most well constructed catch clauses should be to resolve the exceptional condition and then continue on as if the error had never happened.
·         In some cases more than one exception could be raised by a single piece of code. To handle this type of situation you can specify two or more catch clauses, each catching a different type of exception. When an exception is thrown, each catch statement is inspected in order and the first one whose type matches that of the exception is executed. After one catch statement executes, the others are bypassed and execution continues after the try/catch block.
·         It is possible for your program to throw an exception explicitly using the throw statement. There are two ways you can obtain a Throwable object: using a parameter in catch clause or creating one with the new operator.
·         The flow of execution stops immediately after the throw statement; any subsequent statements are not executed. The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of exception. If it does find a match, control is transferred to that statement. If not then the next enclosing try statement is inspected and so on. If no matching catch is found, then default exception handler halts the program and prints the stack trace.
·         If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. You do this by including a throws clause in the method’s declaration. 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 RuntimeException or any of their sub classes.
·         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. 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.


INPUT OUTPUT BASICS

  • Java programs perform I/O through 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. They 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.
  • Java defines two types of streams. Byte stream and character stream. Byte streams provide a convenient means for handling input and output of bytes. Byte streams are used when reading or writing binary data. Character streams provide a convenient means for handling input and output of characters. They use Unicode and can be internationalized. In some cases character streams are more efficient than byte streams.
  • Byte streams are defined by using two class hierarchies. At the top are two abstract classes: InputStream and OutputStream. Each of these abstract classes has several concrete sub classes that handle the differences between the various devices such as disk files, network connections and even memory buffers.
  • Character streams are defined by using two class hierarchies. At the top are two abstract classes: Reader and Writer. These classes handle Unicode character streams.
  • System also contains three predefined stream variables: in, out and err. These fields are declared as public and static 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. This is the console. System.in refers to standard input which is the keyboard by default. System.err refers to the standard error stream which also is the console by default.

READING CONSOLE INPUT
·         In Java, console input is accomplished by reading from System.in. To obtain a character based stream that is attached to the console, you wrap System.in in a BufferedReader object. BufferedReader supports a buffered input stream. Its commonly used constructor is: BufferedReader (Reader inputreader).
·         Reader is an abstract class. One of its concrete sub classes is InputStreamReader which converts bytes to characters. To obtain an InputStreamReader object that is linked to System.in use the following constructor: InputStreamReader (InputStream inputstream).
·         Because System.in refers to an object of type InputStream it can be used for inputstream. Putting it all together the following line of code creates a BufferedReader that is connected to the keyboard:
BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
·         To read a character from a BufferedReader 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.
·         To read a string from the keyboard use the version of readLine () that is a member of the BufferedReader class. Its general form is shown here: String readLine () throws IOException. It returns a String object.
·         PrintWriter is one of the character based classes. Using a character based class for console output makes it easier to internationalize your program. PrintWriter defines several constructors. The most commonly used one is :
PrintWriter (OutputStream outputstream, Boolean flushOnNewline).
Here outputstream is an object of type OutputStream and flushOnNewline controls whether Java flushes the output stream every time a println () method is called.
·         Java provides a number of classes and methods that allow you to read and write files. In Java all files are byte oriented and Java provides methods to read and write bytes from and to a file. Two of the most often used stream classes are FileInputStream and FileOutputStream, which create byte streams linked to files.
·         To open a file you simply create an object of one these classes specifying the name of the file as an argument to the constructor. While both classes support additional overridden constructors, the following forms are commonly used:
FileInputStream (String filename) throws FileNotFoundException
FileOutputStream (String filename) throws FileNotFoundException

·         When you create an input stream if the file does not exist then the exception is thrown. When you are done with a file you should close it by calling close (). To read from a file you can use a version of read () that is defined within FileInputStream.

No comments:

Post a Comment