MODULE 3 1 Syllabus ▪ Packages and Interfaces - Defining Package, CLASSPATH, Access Protection, Importing Packages, Interfaces. Exception Handling - Checked Exceptions, Unchecked Exceptions, try Block and catch Clause, Multiple catch Clauses, Nested try Statements, throw, throws and finally. Input/Output - I/O Basics, Reading Console Input, Writing Console Output, PrintWriter Class, Object Streams and Serialization, Working with Files. 2 Packages 3 4 5 6 7 Predefined package 8 Creating Packages ▪ The general form of creating a package is: 9 ▪ To compile the java programs with package use ▫ javac -d Destinationfolder filename.java 10 ▪ Package names and directory structure are closely related. ▪ For example if a package name is college.staff.cse ▫ Then there are three directories, college, staff and cse such that cse is present in staff and staff is present college. 11 ▪ To use a class or a package from the library, we need to use the import keyword: ▪ Syntax 12 13 14 15 16 17 18 19 20 Interfaces 21 22 What is an interface in Java? Interface looks like a class but it is not a class. An interface can have methods and variables just like the class but the methods declared in interface are by default abstract Also, the variables declared in an interface are public, static & final by default. 23 What is the use of interface in Java? They are used for full abstraction Since methods in interfaces do not have body, they have to be implemented by the class before you can access them The class that implements interface must implement all the methods of that interface. Java programming language does not allow you to extend more than one class, However you can implement more than one interfaces in your class. 24 syntax 25 Interfaces are declared by specifying a keyword “interface”. E.g.: interface MyInterface{ /* All the methods are public abstract by default as you see they have no body */ public void method1(); public void method2(); } 26 27 28 29 30 31 Example interface printable { void print(); } class A6 implements prin table { public void print() { System.out.println("Hell o"); public static void ma in(String args[]) { A6 obj = new A6(); obj.print(); } } Output:Hello 32 33 MODULE 3 1 Syllabus ▪ Packages and Interfaces - Defining Package, CLASSPATH, Access Protection, Importing Packages, Interfaces. Exception Handling - Checked Exceptions, Unchecked Exceptions, try Block and catch Clause, Multiple catch Clauses, Nested try Statements, throw, throws and finally. Input/Output - I/O Basics, Reading Console Input, Writing Console Output, PrintWriter Class, Object Streams and Serialization, Working with Files. 2 I/O Basics Let’s start with the first set of slides 3 Java I/O (Input and Output) is used to process the input and produce the output. Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the classes required for input and output operations. We can perform file handling in Java by Java I/O API 4 Stream 5 A stream is a communication channel that a program has with the outside world. It is used to transfer data items in succession. An I/O Stream represents an input source or an output destination. A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream because it is like a stream of water that continues to flow. 6 Java Stream Classes Based on the data they handle there are two types of streams Byte Streams These handle data in bytes (8 bits) Using these you can store characters, videos, audios, images etc. Character Streams These handle data in 16 bit Unicode. Using these you can read and write text data only. 7 8 ▪ In Java, 3 streams are created for us automatically. ▪ All these streams are attached with the console. 1. System.out : standard output stream 2. System.in : standard input stream 3. System.err : standard error stream ▪ The code to print output and an error message to the console. ▫ System.out.println("simple message"); ▫ System.err.println("error message"); ▪ The code to get input from console. ▫ int i=System.in.read(); //returns ASCII code of 1st character 9 ByteStream ▪ This is used to process data byte by byte (8 bits). ▪ The FileInputStream is used to read from the source and FileOutputStream is used to write to the destination. ▪ the FileInputStream and the FileOutputStream are the most popular ones. 10 ▪ InputStream ▫ A program uses an input stream to read data from a source. ▫ It may be a file, an array, peripheral device or socket. 11 ▪ InputStream class is an abstract class. ▫ It is the super class of all classes representing an input stream of bytes. 12 InputStream - Methods 13 14 ▪ Class DataInputStream extends FileInputStream and implements the interface DataInput. ▪ Therefore, the DataInputStream class implements the methods described in DataInput in addition to using the methods of InputStream class. ▪ The DataInput interface contains the following methods ▫ ▫ ▫ ▫ ▫ ▫ ▫ ▫ ▫ 15 readShort( ) readInt( ) readLong( ) readFloat( ) readUTF( ) readDouble( ) readLine( ) readChar( ) readBoolean( ) ▪ OutputStream ▫ A program uses an output stream to write data to a destination, one item at time ▫ It may be a file, an array, peripheral device or socket 16 ▪ OutputStream class is an abstract class. ▪ It is the superclass of all classes representing an output stream of bytes. ▪ An output stream accepts output bytes and sends them to some sink. 17 18 OutputStream - Methods 19 20 ▪ The DataOutputStream implements the interface DataOutput and therefore implements the following methods contained in Dataoutput interface. ▫ ▫ ▫ ▫ ▫ ▫ ▫ ▫ writeShort( ) writeInt( ) writeLong( ) writeFloat( ) writeUTF( ) writeDouble( ) writeBytes( ) writeChar( ) ▫ writeBoolean( ) 21 STREAM CLASS BufferedInputStream DESCRIPTION It is used for Buffered Input Stream. DataInputStream It contains method for reading java standard datatypes. FileInputStream This is used to reads from a file InputStream This is an abstract class that describes stream input. PrintStream This contains the most used print() and println() method BufferedOutputStream This is used for Buffered Output Stream. DataOutputStream This contains method for writing java standard data types. FileOutputStream This is used to write to a file. OutputStream This is an abstract class that describe stream output. 22 CharacterStream ▪ In Java, characters are stored using Unicode conventions ▪ Character stream automatically allows us to read/write data character by character ▪ FileReader and FileWriter are character streams used to read from the source and write to the destination respectively. ▪ the FileReader and the FileWriter are the most popular ones 23 ▪ Reader Classes ▷ Reader stream classes are used to read characters from the files. ▷ It include a super class known as Reader and a number of subclasses for supporting various input-related functions. ▷ The Reader class contains methods that are is designed to handle characters. 24 25 ▪ Methods of Reader class Methods int read() This method reads a characters from the input stream. int read(char[] ch) This method reads a chunk of characters from the input stream and store them in its char array, ch. close() 26 Description This method closes this output stream and also frees any system resources connected with it. ▷ Writer Classes ▷ the writer stream classes are designed to perform all output operations on files. ▷ the writer stream are designed to write character. ▷ The Writer class is an abstract class which acts as a base class for all the other writer stream classes. ▷ This base class provides support for all output operations by defining methods that are identical to those in 27 Outputstream class. ▪ Methods of Writer class Methods Description abstract void flush() This method flushes the output steam by forcing out buffered bytes to be written out. void write(int c) This method writes a characters(contained in an int) to the output stream. void write(char[] arr) This method writes a whole char array(arr) to the output stream. abstract void close() 28 This method closes this output stream and also free any resources connected with this output stream. 29 STREAM CLASS DESCRIPTION BufferedReader It is used to handle buffered input stream. FileReader This is an input stream that reads from file. InputStreamReader OutputStreamReader Reader PrintWriter Writer This input stream is used to translate byte to character. This output stream is used to translate character to byte. This is an abstract class that define character stream input. This contains the most used print() and println() method This is an abstract class that define character stream output. BufferedWriter This is used to handle buffered output stream. FileWriter This is used to output stream that writes to file. 30 READING CONSOLE INPUT ▪ In Java, there are three different ways for reading input from the user in the command line environment(console). 1. Using Buffered Reader Class 2. Using Console Class 3. Using Scanner class 32 Buffered Reader Class ▪ This is the Java classical method to take input, Introduced in JDK1.0. ▪ This method is used by wrapping the System.in (standard input stream) in an InputStreamReader which is wrapped in a BufferedReader, we can read input from the user in the commandline. 33 Buffered Reader Class ▪ Advantage ▫ The input is buffered for efficient reading ▪ Drawback ▫ The wrapping code is hard to remember. 34 35 Console Class ▪ It has been becoming a preferred way for reading user’s input from the command line. ▪ In addition, it can be used for reading password-like input without echoing the characters entered by the user ▪ The java.io.Console.format(String fmt, Object... args) method writes a formatted string to this console's output stream using the specified format string arguments. ▫ Similar to printf in C 36 Console Class ▪ Advantages: ▫ Reading password without echoing the entered characters. ▫ Reading methods are synchronized. ▫ Format string syntax can be used. ▪ Drawback: ▫ Does not work in non-interactive environment (such as in an IDE). 37 38 WRITING CONSOLE OUTPUT ▪ Console output is most easily accomplished with print() and println() methods. ▪ These methods are defined by the class PrintStream which is the type of object referenced by System.in. ▪ Because the PrintStream is an output stream derived from the OutputStream, it also implements the low-level method write(). ▪ Thus, write() can be used to write to the console. ▪ The simplest form of write() defined by the PrintStream is shown below : ▫ void write(int byteval) 39 40 Scanner Class ▪ most preferred method to take input. ▪ The Scanner class is used to get user input ▪ it is found in the java.util package. 42 // Java program to demonstrate working of Scanner in Java import java.util.Scanner; class GetInputFromUser { public static void main(String args[]) { // Using Scanner for Getting Input from User Scanner in = new Scanner(System.in); String s = in.nextLine(); System.out.println("You entered string "+s); int a = in.nextInt(); System.out.println("You entered integer "+a); float b = in.nextFloat(); System.out.println("You entered float "+b); } } 43 Method Description nextBoolean() Reads a boolean value from the user nextByte() Reads a byte value from the user nextDouble() Reads a double value from the user nextFloat() Reads a float value from the user nextInt() Reads a int value from the user nextLine() Reads a String value from the user nextLong() Reads a long value from the user nextShort() Reads a short value from the user 44 Example import java.util.Scanner; class MyClass { public static void main(String[] args) { Scanner myObj = new Scanner(System.in); String name = myObj.nextLine(); int age = myObj.nextInt(); double salary = myObj.nextDouble(); System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Salary: " + salary); } } 45 PrintWriter CLASS ▪ Java PrintWriter class is the implementation of Writer class. ▪ It is used to print the formatted representation of objects to the text-output stream. ▪ Class declaration ▫ public class PrintWriter extends Writer 47 Method Description void println(boolean x) It is used to print the boolean value. void println(char[] x) It is used to print an array of characters. void println(int x) It is used to print an integer. PrintWriter append(char c) It is used to append the specified character to the writer. PrintWriter append(CharSequence ch) It is used to append the specified character sequence to the writer. PrintWriter append(CharSequence ch, int start, int end) It is used to append a subsequence of specified character to the writer. boolean checkError() It is used to flushes the stream and check its error state. protected void setError() It is used to indicate that an error occurs. protected void clearError() It is used to clear the error state of a stream. PrintWriter format(String format, Object... args) It is used to write a formatted string to the writer using specified arguments and format string. void print(Object obj) It is used to print an object. void flush() It is used to flushes the stream. void close() It is used to close the stream. 48 49 Object Streams and Serialization 50 ▪ Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object. ▪ Serialization in Java allows us to convert an Object to stream that we can send over the network or save it as file or store in DB for later usage ▪ Serialization in Java is a mechanism of writing the state of an object into a byte-stream. ▪ Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. ▪ After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory. 51 ▪ The serialization and deserialization process is platform-independent, it means you can serialize an object on one platform and deserialize it on a different platform ▪ The entire process is JVM independent,meaning an object can be serialized on one platform and deserialized on an entirely different platform. ▪ Classes ObjectInputStream and ObjectOutputStream are highlevel streams that contain the methods for serializing and deserializing an object. ▪ For serializing the object, we call the writeObject() method of ObjectOutputStream, and for deserialization we call the readObject() method of ObjectInputStream class ▪ Its main purpose is to save the state of an object in order to be able to recreate it when needed. 52 ▪ We must have to implement the Serializable interface for serializing the object. ▪ Advantages of Java Serialization ▫ It is mainly used to travel object's state on the network (which is known as marshaling). 53 Object Stream class ▪ The above method serializes an Object and sends it to the output stream. Similarly, the ObjectInputStream class contains the following method for deserializing an object ▪ This method retrieves the next Object out of the stream and deserializes it. The return value is Object, so you will need to cast it to its appropriate data type 54 How it works? Consider a class Employee 55 • The class must implement the java.io.Serializable interface. • All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient. Serializing an Object • The ObjectOutputStream class is used to serialize an Object. • SerializeDemo program instantiates an Employee object and serializes it to a file. • When the program is done executing, a file named employee.ser is created. • When 56 object serializing to a file, an the Deserializing an Object The following DeserializeDemo program deserializes the Employee object created in the SerializeDemo program • • 57 The value of the SSN field was 11122333 when the object was serialized, but because the field is transient, this value was not sent to the output stream. The SSN field of the deserialized Employee object is 0 The try/catch block tries to catch a ClassNotFoundException, which is declared by the readObject() method. For a JVM to be able to deserialize an object, it must be able to find the bytecode for the class. If the JVM can't find a class during the deserialization of an object, it throws a ClassNotFoundException. MODULE 3 1 Syllabus ▪ Packages and Interfaces - Defining Package, CLASSPATH, Access Protection, Importing Packages, Interfaces. Exception Handling - Checked Exceptions, Unchecked Exceptions, try Block and catch Clause, Multiple catch Clauses, Nested try Statements, throw, throws and finally. Input/Output - I/O Basics, Reading Console Input, Writing Console Output, PrintWriter Class, Object Streams and Serialization, Working with Files. 2 Files 3 ▪ File handling is an important part of any application. ▪ Data maintained in files is persistent data because it exists beyond the duration of program execution. ▪ Java has several methods for creating, reading, updating, and deleting files. ▪ The File class from the java.io package, allows us to work with files. 4 ▪ The File class from the java.io package, allows us to work with files. ▪ To use the File class, create an object of the class, and specify the filename or directory name 5 6 ▪ Create a File ▫ To create a file in Java, you can use the createNewFile() method. ▫ This method returns a boolean value: true if the file was successfully created, and false if the file already exists. ▫ the method is enclosed in a try...catch block. ▫ This is necessary because it throws an IOException if an error occurs (if the file cannot 7 be created for some reason): 8 ▪ Write To a File ▫ we use the FileWriter class together with its write() method to write some text to the file we created ▫ Note that when we are done writing to the file, we should close it with the close() method 9 10 Read Files 11 Get File Information 12 Delete a File • To delete a file in Java, use the delete() method: 13 Delete a Folder 14 Java FileInputStream ▪ The Java FileInputStream class, java.io.FileInputStream, makes it possible to read the contents of a file as a stream of bytes. ▪ Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data (streams of raw bytes) such as image data, audio, video etc. ▪ You can also read character-stream data. But, for reading streams of characters, it is recommended to use FileReader class. ▪ The Java FileInputStream class is a subclass of Java InputStream. FileInputStream Constructors ▪ The FileInputStream class has different constructors you can use to create a FileInputStream instance. ▪ Two commonly used constructors are ▫ FileInputStream(String filePath) String path = "C:\\user\\data\\thefile.txt"; FileInputStream fileInputStream = new FileInputStream(path); ▫ FileInputStream (File FileIObj) String path = "C:\\user\\data\\thefile.txt"; File file = new File(path); FileInputStream fileInputStream = new FileInputStream(file); Java FileInputStream ▪ Methods of FileInputStream The FileInputStream class provides implementations for different methods present in the InputStream class. read() Method ▪ read() - reads a single byte from the file ▪ read(byte[] array) - reads the bytes from the file and stores in the specified array ▪ read(byte[] array, int start, int length) - reads the number of bytes equal to length from the file and stores in the specified array starting from the position start Java FileInputStream FileInputStream - Important Methods: Method Description int available() It is used to return the estimated number of bytes that can be read from the input stream. int read() It is used to read the byte of data from the input stream. int read(byte[] b) It is used to read up to b.length bytes of data from the input stream. int read(byte[] b, int off, int len) It is used to read up to len bytes of data from the input stream. b − The destination byte array, off − The start offset in array b at which the data is written, len − The number of bytes to read. long skip(long x) It is used to skip over and discards x bytes of data from the input stream. FileDescriptor getFD() It is used to return the FileDescriptor object. void close() It is used to closes the stream. Java FileOutputStream ▪ FileOutputStream is an output stream for writing data to a File or to a FileDescriptor. ▪ FileOutputStream is a subclass of OutputStream, which accepts output bytes and sends them to some sink. ▪ In case of FileOutputStream, the sink is a file object. Java FileOutputStream Example-Write a byte Output: success It writes character ‘A’ to file Java FileOutputStream Example-Write string to a file Output: success It writes “Welcome to javaTpoint” to the file Java FileOutputStream constructors ▪ FileOutputStream(File file) ▷ creates a file output stream to write to a File object. ▪ FileOutputStream(File file, boolean append) ▷ creates a file output stream to write to a File object; allows appending mode. ▪ FileOutputStream(String name) ▷ creates a file output stream to write to the file with the specified name. ▪ FileOutputStream(String name, boolean append) ▷ creates a file output stream to write to the file with the specified name; allows appending mode. Java FileOutputStream constructors ▪ FileOutputStream(String name) String path = "C:\\users\\jakobjenkov\\ data\\datafile.txt"; FileOutputStream output = new FileOutputStream(path); ▪ FileOutputStream(File file) String path = "C:\\users\\jakobjenkov\\data\\ datafile.txt"; File file = new File(path); FileOutputStream output = new FileOutputStream(file); Java FileOutputStream constructors ▪ FileOutputStream(String name, boolean append) OutputStream output = new FileOutputStream("c:\\data\\outputtext.txt"); OutputStream output = new FileOutputStream("c:\\data\\outputtext.txt", true); //append OutputStream output = new FileOutputStream("c:\\data\\outputtext.txt", false); //overwrite FileOutputStream Important Methods: Method Description void write(byte[] ary) It is used to write ary.length bytes from the byte array to the file output stream. void write(byte[] ary, int off, int len) It is used to write len bytes from the byte array starting at offset off to the file output stream. void write(int b) It is used to write the specified byte to the file output stream. void close() It is used to closes the file output stream. Java FileReader ▪ The Java FileReader class, java.io.FileReader makes it possible to read the contents of a file as a stream of characters. ▪ It works much like the FileInputStream except the FileInputStream reads bytes, whereas the FileReader reads characters. ▪ The FileReader is intended to read text, in other words. ▪ One character may correspond to one or more bytes depending on the character encoding scheme. ▪ Java FileReader 29 Java FileReader Example Reader fileReader = new FileReader("c:\\data\\inputtext.txt"); int data = fileReader.read(); while(data != -1) { //do something with data... doSomethingWithData(data); data = fileReader.read(); } fileReader.close(); Constructors of FileReader class Constructor Description FileReader(String file) It gets filename in string. It opens the given file in read mode. If file doesn't exist, it throws FileNotFoundException. FileReader(File file) It gets filename in file instance. It opens the given file in read mode. If file doesn't exist, it throws FileNotFoundException. Methods of FileReader class Method Description public int read() Reads a single character. Returns represents the character read. Public int read(char[] charArray) Used to read the specified characters into an array public int read(char [] charArray, int offset, int len) Reads characters into an array. Returns the number of characters read. public long skip(long n) skips the character. n - It is the number of character to skip. It returns the number of character which has been skipped. All Methods throws IOException an int, which Java FileWriter ▪ Java FileWriter class is a part of java.io package. ▪ FileWriter is meant for writing streams of characters. ▪ FileWriter is used to write to character files. Its write() methods allow you to write character(s) or strings to a file. Java FileWriter 35 FileWriter Constructors ▪ FileWriter(File file) ▪ FileWriter(File file, boolean append) ▪ FileWriter(String fileName) ▪ FileWriter(String fileName, boolean append) Exception Handling in java What is an Exception? ▪ An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the program’s instructions. ▪ Exception indicates conditions that a reasonable application might try to catch. ▪ Example for exceptions are, arithmetic exception, Nullpointer exception, Divide by zero exception, etc. Exception vs. Error ▪ Exceptions and errors both are subclasses of Throwable class ▪ Error indicate that something severe enough has gone wrong, the application should crash rather than try to handle the error.Some of the examples of errors are system crash error and out of memory error etc. Errors mostly occur at runtime that's they belong to an unchecked type. ▪ Exceptions are the problems which can occur at runtime and compile time. It mainly occurs in the code written by the developers. These are events that occurs in the code. A programmer can handle such conditions and take necessary corrective actions. Exception Common scenarios where exceptions may occur ▪ There can be several reasons that can cause a program to throw exception. ▪ For example: Opening a non-existing file in your program, Network connection problem, bad input data provided by user etc. 5 Common scenarios where exceptions may occur ▪ Scenario where ArithmeticException occurs ▫ If we divide any number by zero, there occurs an ArithmeticException. ▫ int a=50/0; //ArithmeticException 6 Common scenarios where exceptions may occur ▪ Scenario where NullPointerException occurs String s=null; System.out.println(s.length()); 7 Common scenarios where exceptions may occur ▪ Scenario where NumberFormatException occurs String s="abc"; int i=Integer.parseInt(s); //NumberFormatException 8 Common scenarios where exceptions may occur ▪ Scenario where ArrayIndexOutOfBoundsException occurs int a[]=new int[5]; a[10]=50; //ArrayIndexOutOfBoundsException 9 Types of Java Exceptions ▪ There are mainly two types of exceptions: checked and unchecked. ▪ Here, an error is considered as the unchecked exception. ▪ According to Oracle, there are three types of exceptions: ▫ Checked Exception ▫ Unchecked Exception ▫ Error 1 0 Checked Exception ▫ Checked exceptions are checked at compile-time. ▫ It means if a method is throwing a checked exception then it should handle the exception using try-catch block or it should declare the exception using throws keyword, otherwise the program will give a compilation error. ▫ The classes which directly inherit Throwable class except RuntimeException and Error are known as checked exceptions ▫ e.g. IOException, SQLException etc. 1 1 Unchecked Exception ▫ ▫ ▫ ▫ ▫ ▫ Unchecked exceptions are checked at runtime It means if your program is throwing an unchecked exception and even if you didn’t handle/declare that exception, the program won’t give a compilation error. these exception occurs due to the bad data provided by user during the user-program interaction. Programmer has to judge the conditions in advance, that can cause such exceptions and handle them appropriately. All Unchecked exceptions are direct sub classes of RuntimeException class.The classes which inherit RuntimeException are known as unchecked exceptions. 1 2 Eg:ArithmaticException Unchecked Exception-Example If you compile this code, it would compile successfully however when you will run it,it would throw ArithmeticException. That clearly shows that unchecked exceptions are not checked at compiletime, they occurs at runtime. 1 3 Error ▫ Error is irrecoverable ▫ e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc. 1 4 Exception Handling ▪ Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException,RemoteException, etc ▪ The core advantage of exception handling is to maintain the normal flow of the application ▪ An exception normally disrupts the normal flow of the application that is why we use exception handling ▪ Exception handling ensures that the flow of the program doesn’t break when an exception occurs ▪ Exception handling is one of the most important feature of java programming that allows us to handle the runtime errors caused by exceptions. . 1 5 Exception Handling ▪ Let's take a scenario: ▫ Suppose there are 10 statements in your program and there occurs an exception at statement 5, the rest of the code will not be executed i.e. statement 6 to 10 will not be executed. ▫ If we perform exception handling, the rest of the statement will be executed. That is why we use exception 1 6 Java Exception Handling Keywords 1 7 try Block and catch Clause 18 try…catch ▪ The try statement allows you to define a block of code to be tested for errors while it is being executed. ▪ The catch statement allows you to define a block of code to be executed, if an error occurs in the try block ▪ The try and catch keywords come in pairs 1 9 try …catch try { //statements that may cause an exception } catch (exception(type) e(object)) { //error handling code 2 0 try …catch Consider the example, This will generate an error, because myNumbers[10] does not exist.If an error occurs, we can use try...catch to catch the error and execute some code to handle it 2 1 22 23 Internal working of java try-catch block 24 ▪ The JVM firstly checks whether the exception is handled or not. ▪ If exception is not handled, JVM provides a default exception handler that performs the following tasks: ▫ Prints out exception description. ▫ Prints the stack trace (Hierarchy of methods where the exception occurred). ▫ Causes the program to terminate. ▪ But if exception is handled by the application programmer, normal flow of the application is 2 maintained i.e. rest of the code is executed. 5 Multiple catch Clauses 26 Multiple catch Clauses • A try block can be followed by one or more catch blocks ▪ Each catch block must contain a different exception handler. ▪ So, if you have to perform different tasks at the occurrence of different exceptions, use java multi-catch block. ▪ At a time only one exception occurs and at a time only one catch block is executed. ▪ All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must come before catch for Exception. 2 7 28 Nested try Statements 29 Nested try Statements ▪ The try block within a try block is known as nested try block in java. ▪ Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error ▪ In such cases,exception handlers have to be nested. 3 0 31 finally block 32 finally block ▪ Java finally block is a block that is used to execute important code such as closing connection, stream etc. ▪ Java finally block is always executed whether exception is handled or not ▪ Java finally block follows try or catch block. ▪ Note: If you don't handle exception, before terminating the program, JVM executes finally block(if any). 3 3 3 4 Usage of Java finally ▪ Case 1 - Let's see the java finally example where exception doesn‘t occur. 3 5 ▪ Case 2 - Let's see the java finally example where exception occurs and not handled. 3 6 ▪ Case 3 - Let's see the java finally example where exception occurs and handled 3 7 finally.. ▪ A finally block must be associated with a try block, you cannot use finally without a try block. ▪ You should place those statements in this block that must be executed always. ▪ Finally block is optional, however if you place a finally block then it will always run after the execution of try block. 3 8 finally.. ▪ if an exception occurs then the catch block is executed before finally block. ▪ An exception in the finally block, behaves exactly like any other exception. ▪ The statements present in the finally block execute even if the try block contains control transfer statements like return, break or continue. 3 9 finally.. 4 0 throw keyword 41 throw ▪ The Java throw keyword is used to explicitly throw an exception from a method or any block of code. ▪ We can define our own set of conditions or rules and throw an exception explicitly using throw keyword ▪ For example, we can throw ArithmeticException when we divide number by 5, or any other numbers, what we need to do is just set the condition and throw any exception using throw keyword. ▪ Throw keyword can also be used for throwing custom exceptions ▪ Syntax of throw keyword: throw new exception-class("error message"); For example: throw new ArithmeticException("dividing a number by 5 is not allowed in this program"); 4 2 43 Lets say we have a requirement where we we need to only register the students when their age is less than 12 and weight is less than 40, if any of the condition is not met then the user should get an ArithmeticException with the warning message “Student is not eligible for registration”. We have implemented the logic by placing the code in the method that checks student eligibility if the entered student age and weight doesn’t met the criteria then we throw the exception using throw keyword. 4 4 throw.. ▪ The flow of execution of the program stops immediately after the throw statement is executed ▪ the nearest enclosing try block is checked to see if it has a catch statement that matches the type of exception. ▪ If it finds a match, controlled is transferred to that statement otherwise next enclosing try block is checked and so on. ▪ If no matching catch is found then the default exception handler will halt the program. ▪ instance must be of type Throwable or a subclass of Throwable. ▪ For example Exception is a sub-class of Throwable 4 5 Output: 46 Caught inside fun(). Caught in main. throws keyword 47 throws ▪ The Java throws keyword is used to declare an exception. ▪ throws is a keyword in Java which is used in the signature of method to indicate that this method might throw one of the listed type exceptions. ▪ The caller to these methods has to handle the exception using a try-catch block. ▪ Exception Handling is mainly used to handle the checked exceptions. ▪ 4 8 throws ▪ The throws does the same thing that try-catch does but there are some cases where you would prefer throws over try-catch. ▪ For example: Lets say we have a method myMethod() that has statements that can throw either ArithmeticException or NullPointerException, in this case you can use try-catch as shown below: But suppose you have several such methods that can cause exceptions, in that case it would be tedious to write these try-catch for each method. The code will become unnecessary long and will be less-readable. 4 . 9 throws ▪ One way to overcome this problem is by using throws like this: ▪ declare the exceptions in the method signature using throws and handle the exceptions where you are calling this method by using try-catch. ▪ Another advantage of using this approach is that you will be forced to handle the exception when you call this method, all the exceptions that are declared using throws, must be handled where you are calling this method else you will get compilation error 5 0 throws.. ▪ Syntax: ▫ type methodname(parameters) throws exceptionlist ▫ exceptionlist is a comma separated list of all the exceptions which a method might throw. 5 1 52 53 54