JAVA Notes - Unit 5.pdf
Document Details
Uploaded by BraveArtInformel
Full Transcript
JAVA PROGRAMMING UNIT-5 EXCEPTION HANDLING AND MULTITHREADED PROGRAMMING 5.1 TYPES OF ERROR 1.Compile-time Errors: Compile-time errors, also known as compilation errors or syntax errors, occur during the compilation phase of the program...
JAVA PROGRAMMING UNIT-5 EXCEPTION HANDLING AND MULTITHREADED PROGRAMMING 5.1 TYPES OF ERROR 1.Compile-time Errors: Compile-time errors, also known as compilation errors or syntax errors, occur during the compilation phase of the program. These errors are caused by violations of the Java syntax rules or incorrect usage of language constructs. Examples of compile-time errors include missing semicolons, undefined variables, incompatible types, or using a reserved keyword as an identifier. When a compile-time error occurs, the compiler generates an error message, and the program cannot be compiled until the errors are fixed. 2.Runtime Errors: Runtime errors, also called exceptions, occur during the execution of the program. These errors are caused by exceptional conditions or unexpected situations that arise while the program is running. Common examples of runtime errors include division by zero (ArithmeticException), accessing an array element with an invalid index (ArrayIndexOutOfBoundsException), or attempting to open a non-existent file (FileNotFoundException). When a runtime error occurs, an exception object is thrown, which can be caught and handled using exception handling mechanisms like try-catch blocks. If unhandled, the program terminates abruptly. 3.Logical Errors: Logical errors, also known as semantic errors or bugs, occur when the program's logic or algorithm is incorrect. These errors do not cause the program to crash or generate error messages but result in undesired or incorrect behavior. Logical errors can be challenging to identify as they do not produce any compile-time or runtime errors. The program runs successfully, but the output or behavior is not as expected. Detecting and fixing logical errors typically involves careful code review, debugging, and testing. It is important to note that compile-time errors are caught by the compiler during the compilation process, runtime errors occur during program execution and can be caught and handled using exception handling, while logical errors require careful analysis and debugging to identify and fix. JAVA PROGRAMMING 5.2 BASIC CONCEPTS OF EXCEPTION HANDLING Exception handling in Java is a mechanism that allows you to handle and recover from exceptional situations or errors that occur during the execution of a program. It helps in making the program more robust by providing a structured approach to deal with unexpected or exceptional scenarios. Exception An exception is an event that occurs during the execution of a program and disrupts the normal flow of the program. Exceptions represent various types of errors, such as runtime errors, input/output errors, arithmetic errors, and others. In Java, exceptions are represented by classes that are derived from the Throwable class or one of its subclasses. Types of Exception: 1. Built-in Exception Exceptions that are already available in Java libraries are referred to as built-in exception. Checked Exception: Checked exceptions are called compile-time exceptions because these exceptions are checked at compile- time by the compiler. EXAMPLE: import java.io.*; class CheckedExceptionExample { JAVA PROGRAMMING public static void main(String args[]) { FileInputStream file_data = null; file_data = new FileInputStream("C:/Users/ajeet/OneDrive/Desktop/Hello.txt"); int m; while(( m = file_data.read() ) != -1) { System.out.print((char)m); } file_data.close(); } } Unchecked Exception: The unchecked exceptions are just opposite to the checked exceptions. The compiler will not check these exceptions at compile time. In simple words, if a program throws an unchecked exception, and even if we didn't handle or declare it, the program would not give a compilation error. Usually, it occurs when the user provides bad data during the interaction with the program. EXAMPLE: class UncheckedExceptionExample1 { public static void main(String args[]) { int postive = 35; int zero = 0; int result = positive/zero; //Give Unchecked Exception here. System.out.println(result); } } JAVA PROGRAMMING 2. User-defined Exception we can write our own exception class by extends the Exception class. We can throw our own exception on a particular condition using the throw keyword. For creating a user-defined exception, we should have basic knowledge of the try-catch block and throw keyword. EXAMPLE: import java.util.*; class UserDefinedException { public static void main(String args[]) { try{ throw new NewException(5); } catch(NewException ex) { System.out.println(ex); } } } class NewException extends Exception { int x; NewException(int y) { x=y; } public String toString() { return ("Exception value = "+x) ; } } JAVA PROGRAMMING 5.3 TRY AND CATCH BLOCK The try-catch block is used to handle exceptions and provide a mechanism to gracefully handle exceptional situations during the execution of a program. The try-catch block consists of a try block and one or more catch blocks. try { // Code that may throw an exception } catch (ExceptionType1 ex1) { // Exception handling code for ExceptionType1 } catch (ExceptionType2 ex2) { // Exception handling code for ExceptionType2 } catch (Exception ex) { // Generic exception handling code for any other exception } If an exception occurs within the try block, the control immediately transfers to the corresponding catch block based on the type of exception. Each catch block specifies the type of exception it can handle. If the caught exception matches the type specified in a catch block, that catch block is executed. If no catch block is found that matches the type of the thrown exception, the exception propagates to the next level of the method call stack or terminates the program if it reaches the main method without being caught. EXAMPLE: public class Main { public static void main(String[ ] args) { try { int[] myNumbers = {1, 2, 3}; System.out.println(myNumbers); } catch (Exception e) { System.out.println("Something went wrong."); } } } JAVA PROGRAMMING 5.3.1 Multiple Catch Block EXAMPLE: public class MultipleCatchBlock1 { public static void main(String[] args) { try { int a[]=new int; a=30/0; } 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"); } } JAVA PROGRAMMING 5.4 THROW AND THROWS throw and throws are two keywords used in exception handling to deal with exceptions and specify exception propagation. 1.throw Keyword: The throw keyword is used to explicitly throw an exception from within a method or a block of code. It is followed by an instance of an exception class or a subclass of Throwable. When a throw statement is encountered, the normal flow of the program is disrupted, and the specified exception is thrown. It allows you to generate and throw exceptions explicitly to handle exceptional scenarios. EXAMPLE: public class TestThrow1 { //function to check if person is eligible to vote or not public static void validate(int age) { if(age