CGB1201 - Java Programming Module III PDF
Document Details
Uploaded by Deleted User
CGB1201
Tags
Summary
This document appears to be a Java programming module, covering exception handling mechanisms and I/O streams. It details concepts like exception hierarchy, built-in exceptions, and custom exceptions, alongside I/O stream operations.
Full Transcript
CGB1201 - Java Programming Module III EXCEPTION HANDLING AND I/O STREAMS Syllabus Exception Handling Mechanisms -Exception Hierarchy throwing and catching exceptions - built-in exceptions, creating own exceptions - I/O streams Writing Files Readi...
CGB1201 - Java Programming Module III EXCEPTION HANDLING AND I/O STREAMS Syllabus Exception Handling Mechanisms -Exception Hierarchy throwing and catching exceptions - built-in exceptions, creating own exceptions - I/O streams Writing Files Reading and Writing Console Reading and Exception Handling The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that the normal flow of the application can be maintained. Uncaught Exceptions Lets understand exceptions with an example. When we don't handle the exceptions, it leads to unexpected program termination. In this program, an ArithmeticException will be throw due to division by zero. Program: class UncaughtException { public static void main(String args[]) { int a = 0; int b = 7/a; // Divide by zero, will lead to exception } } Output: Unit IV Page 1 CGB1201 - Java Programming This will lead to an exception at runtime, hence the Java run-time system will construct an exception and then throw it. As we don't have any mechanism for handling exception in the above program, hence the default handler (JVM) will handle the exception and will print the details of the exception on the terminal. Java Exception A Java Exception is an object that describes the exception that occurs in a program. When an exceptional event occurs in java, an exception is said to be thrown. The code that's responsible for doing something about the exception is called an exception handler How to Handle Exception Java provides controls to handle exception in the program. These controls are listed below. 1. Try : The try statement allows you to define a block of code to be tested for errors while it is being executed. 2. Catch: The catch statement allows you to define a block of code to be executed, if an error occurs in the try block. 3. Finally: The "finally" block is used to execute the necessary code of the program. It is executed whether an exception is handled or not.. 4. Throw: It throws the exception explicitly. 5. Throws: The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the method. It doesn't throw an exception. It is always used with method signature. Unit IV Page 2 CGB1201 - Java Programming Java Exception Hierarchy Types of Java Exceptions In Java, exceptions broadly can be categorized into checked exception, unchecked exception and error based on the nature of exception. 1. Checked Exception The exception that can be predicted by the JVM at the compile time. For example : File that needs to be opened is not found, SQLException etc. These types of exceptions must be checked at compile time. 2. Unchecked Exception Unchecked exceptions are the class that extends the RuntimeException class. Unchecked exceptions are ignored at compile time and checked at runtime. For example : ArithmeticException, NullPointerException, Array Index out of Bound exception. Unchecked exceptions are checked at runtime. Unit IV Page 3 CGB1201 - Java Programming 3.Error Errors are typically ignored in code because you can rarely do anything about an error. For example, if stack overflow occurs, an error will arise. This type of error cannot be handled in the code. try and catch in Java Try and catch both are Java keywords and used for exception handling. The try block is used to enclose the suspected code. Suspected code is a code that may raise an exception during program execution. Syntax try{ Unit IV Page 4 CGB1201 - Java Programming // suspected code } catch(ExceptionClass ec){} Exception handling is done by transferring the execution of a program to an appropriate exception handler (catch block) when exception occurs. Example: Handling Exception Now lets understand the try and catch by a simple example in which we are dividing a number by zero. The code is enclosed into try block and a catch handler is provided to handle the exception. Program: class Excp { public static void main(String args[]) { int a,b,c; try { a = 0; b = 10; c = b/a; System.out.println("This line will not be executed"); } catch(ArithmeticException e) { System.out.println("Divided by zero"); } System.out.println("After exception is handled"); } } Output: Divided by zero After exception is handled Unit IV Page 5 CGB1201 - Java Programming Explanation An exception will thrown by this program as we are trying to divide a number by zero inside try block. The program control is transferred outside try block. Thus the line "This line will not be executed" is never parsed by the compiler. The exception thrown is handled in catch block. Once the exception is handled, the program control is continue with the next line in the program i.e after catch block. Thus the line "After exception is handled" is printed. Multiple catch blocks A try block can be followed by multiple catch blocks. It means we can have any number of catch blocks after a single try block. If an exception occurs in the guarded code(try block) the exception is passed to the first catch block in the list. If the exception type matches with the first catch block it gets caught, if not the exception is passed down to the next catch block. This continue until the exception is caught or falls through all catches. Syntax try { // suspected code } catch(Exception1 e) { // handler code } catch(Exception2 e) { // handler code } Unit IV Page 6 CGB1201 - Java Programming Example: Multiple Exception Lets understand the use of multiple catch handler by one more example, here we are using three catch handlers in catch the exception. Program: public class MultipleCatchBlock2 { public static void main(String[] args) { try{ int a[]=new int; System.out.println(a); } catch(ArithmeticException e) { System.out.println("Arithmetic Exception occurs"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("ArrayIndexOutOfBounds Exception occurs"); } catch(Exception e) { System.out.println("Parent Exception occurs"); } System.out.println("rest of the code"); } } Output: ArrayIndexOutOfBounds Exception occurs rest of the code Unit IV Page 7 CGB1201 - Java Programming At a time, only one exception is processed and only one respective catch block is executed Java throw, throws and finally Keyword Java Throw The throw keyword is used to throw an exception explicitly. Only object of the Throwable class or its subclasses can be thrown. Program execution stops on encountering a throw statement, and the closest catch statement is checked for matching type of exception. Syntax throw new exception_class("error message"); Program: public class TestThrow1 { //function to check if person is eligible to vote or not public static void validate(int age) { if(age