Exception Handling Lecture Notes PDF

Document Details

Mohamedbouaouni05

Uploaded by Mohamedbouaouni05

Youssef Elmir

Tags

exception handling java programming computer science

Summary

These lecture notes cover exception handling in Java. Topics include introduction to exceptions, types of errors (syntax, runtime, logic), and methods for handling exceptions such as try-catch blocks, throws keyword, and finally block. The notes also cover custom exceptions and the Throwable class.

Full Transcript

Exception handling Introduction Exceptions Types of exceptions Handling an exception Throwing an exception DR. YOUSSEF ELMIR [email protected] Exception handling 2 INTRODUCTION Dr. Youss...

Exception handling Introduction Exceptions Types of exceptions Handling an exception Throwing an exception DR. YOUSSEF ELMIR [email protected] Exception handling 2 INTRODUCTION Dr. Youssef Elmir ([email protected]) Exception handling 3  Introduction  Software is correct if it performs the task for which it was designed effectively.  Software is robust if it can function properly even in the presence of errors. Example: A program that reads numbers entered by the user and displays them in ascending order is correct if it consistently produces the correct result regardless of the numbers entered. It is considered robust if, in addition, it handles non-numeric data appropriately by either displaying an error message or ignoring such input. Dr. Youssef Elmir ([email protected]) Exception handling 4  Introduction During the development and execution of an application, several errors can occur:  Syntax errors: These are very common and occur at compile time (e.g., misspelled keywords).  Runtime errors: These errors appear during execution. The syntax is correct, but the application environment does not allow the execution of a program instruction (e.g., file opening, pointer errors, capacity overflow, etc.).  Logic errors: There are no syntax or execution errors, but the results obtained are not as expected. Dr. Youssef Elmir ([email protected]) Exception handling 5  Introduction  Even if a program is correct, its execution can be interrupted unexpectedly due to exceptional events (incorrect data types, premature end of tables or files, etc.). These events are called Exceptions. “An exception is an event that happens while a program is running and causes it to stop its usual operation.” Dr. Youssef Elmir ([email protected]) Exception handling 6  Introduction  The designer of a program must first try to predict (anticipate) possible errors :  By adding test sequences to prevent them,  By setting up a system to signal abnormal program operation by returning specific values  But none of these solutions is satisfactory because:  it is very difficult to count all the possible errors without omitting any ,  writing the code becomes tedious and complex and its maintenance difficult because of its illegibility (drowned in test overlaps) Dr. Youssef Elmir ([email protected]) Exception handling 7  Exceptions  Java offers a highly flexible mechanism called exception handling, which enables you to identify and manage errors that may occur during program execution.  This mechanism is employed to address the abnormal operation of specific sections of the code. Dr. Youssef Elmir ([email protected]) Exception handling 8  Exceptions  Example public class TestException { public static void main(java.lang.String[] args) { int i = Integer.parseInt(args ); int j = Integer.parseInt(args ); System.out.println("result =" +(i/j)); } }  If the user enters zero as the second value, the following message will be displayed: Exception in thread "main" java.lang.ArithmeticException : / by zero at TestException.main (TestException.java:6) Dr. Youssef Elmir ([email protected]) Exception handling 9 TYPES OF EXCEPTIONS Dr. Youssef Elmir ([email protected]) Exception handling 10  Types of exceptions There are three types of exceptions: Errors(serious errors) Exceptions (common errors) RuntimeExceptions (language errors) Dr. Youssef Elmir ([email protected]) Exception handling 11  Types of exceptions  Inheritance hierarchy of exceptions Throwable Error Exception Runtime Checked Exception Exception Dr. Youssef Elmir ([email protected]) Exception handling 12  Types of exceptions  Types: 1. Error These are serious problems outside of the program's control, like loading classes into memory or hardware issues. They can't be expected or fixed. They're called Error or subclasses like Virtual Machine Error or IOError. Example: Imagine an app opens a file but can't read it because of a hardware or OS problem. Dr. Youssef Elmir ([email protected]) Exception handling 13  Types of exceptions  Types: 2. Checked Exceptions These are errors that a good program should expect and handle. They're called Checked Exceptions, and they're of type Exception. Example: Say an app asks for a file name, but the user enters a name for a file that doesn't exist. This can trigger an exception like java.io.FileNotFound. A well-written program should handle this by informing the user and asking for a valid file name. Dr. Youssef Elmir ([email protected]) Exception handling 14  Types of exceptions  Types: 3. RuntimeException  RuntimeException is a subclass of Exception.  These are errors that occur within the program and the JVM itself, related to the language, and can be handled by the programmer.  These exceptions include arithmetic errors (e.g., division by zero), pointer errors (trying to access an object with a null reference) and indexing errors (index out of bounds). Example: If we pass null instead of a file name to a method in an application, it will trigger a NullPointerException. Dr. Youssef Elmir ([email protected]) Exception handling 15  Types of exceptions  Inheritance hierarchy of exceptions Throwable Error Exception Runtime Checked Exception Exception Standard Custom Exception Exception Dr. Youssef Elmir ([email protected]) Exception handling 16  Types of exceptions  Inheritance hierarchy of exceptions Unchecked Throwable exceptions Error Exception Runtime Checked Exception Exception Standard Custom Exception Exception Dr. Youssef Elmir ([email protected]) Exception handling 17  Types of exceptions  Inheritance hierarchy of exceptions Unchecked The compiler force Throwable exceptions the program to handle them Error Exception Runtime Checked Exception Exception Standard Custom Exception Exception Dr. Youssef Elmir ([email protected]) Exception handling 18 HANDLING AN EXCEPTION Dr. Youssef Elmir ([email protected]) Exception handling 19  Handling an exception  A checked exception is an exception that extends the Exception class. It can be standard (defined in JDK) or customized.  A well-written Java program containing code that might produce a checked exception should attempt to handle it in one of two ways: 1. By catching it with a try-catch block. 2. By propagating it with the throws keyword. Dr. Youssef Elmir ([email protected]) Exception handling 20  Handling an exception  The try-catch block (1) The "try" clause encapsulates a block of code that represents the normal operation of the program but has the potential to generate errors. try { …… } Dr. Youssef Elmir ([email protected]) Exception handling 21  Handling an exception  The try–catch block (2) The "catch" clause specifies a block of code that handles a specific type of exception. This code is executed when an instance of the exception class specified in the catch parameter is thrown. try { …} catch (ExceptionType1 e1) { …} catch(ExceptionType2 e2) { …} Dr. Youssef Elmir ([email protected]) Exception handling 22  Handling an exception  The try–catch block (3) Example : public class TestException2 { public static void main(java.lang.String [] args) { // Insert code to start the application here. int i = Integer.parseInt(args ); int j = Integer.parseInt(args ); try { System.out.println ("result = " + (i/j)); } catch ( ArithmeticException e) { System.out.println("Division by zero"); }}} Dr. Youssef Elmir ([email protected]) Exception handling 23  Handling an exception  The try-catch block (4) What happens when an exception occurs? At any point during the execution of a program, a statement or method may encounter a problem that it cannot handle. When this happens, it throws an exception. A method can either handle the exception itself by using a try-catch block, or it can allow the exception to pass to the method that called it. This method then has the choice to catch the exception or let it pass further up the call chain. Dr. Youssef Elmir ([email protected]) Exception handling 24  Handling an exception  The try-catch block (5) What happens when an exception is thrown? In the first case, if the exception occurs outside of a try block: 1. The method immediately stops execution. 2. The exception is passed back to the calling method. 3. Control is transferred to the calling method. 4. The calling method can choose to catch and handle the exception or allow it to propagate further up the call stack. Dr. Youssef Elmir ([email protected]) Exception handling 25  Handling an exception  The try-catch block (6) What happens when an exception is thrown? In the second case, if the exception occurs within a try block:  If an exception is raised by a statement within the try block: 1. Subsequent statements within the try block are skipped. 2. If there is a catch block that matches the type of the exception: The corresponding catch block is executed. Execution continues after the try-catch block. If there is no matching catch block: The method immediately stops execution. The exception is passed back to the calling method. Dr. Youssef Elmir ([email protected]) Exception handling 26  Handling an exception  The try-catch block (7) What happens when an exception is thrown? 1. If the statements within the try block do not cause exceptions:  The try block proceeds as if there were no try-catch block.  The program continues execution after the try-catch block. 2. If the catch block is empty (no instructions between the braces), the caught exception is ignored. However, this usage is not recommended. It's better to provide appropriate treatment when catching an exception. Dr. Youssef Elmir ([email protected]) Exception handling 27  Handling an exception  The try-catch block (8) What happens when an exception is thrown? 3. Avoid catching an exception by simply displaying a generic message in the catch block that does not provide information about the problem. Instead, display what the printStackTrace method shows, which helps in identifying and resolving the issue. 4. If a variable is declared inside a try block, it cannot be accessed inside a catch block. Common variables should be declared outside the try-catch block to ensure they are accessible throughout the code. Dr. Youssef Elmir ([email protected]) Exception handling 28  Handling an exception  The try –catch blockc (9) And what if the exception is not handled? If an exception propagates back to the main method without being handled by any method along the way, The program execution is halted. An error message associated with the exception is displayed, including a description of the sequence of method calls that led to the exception. Dr. Youssef Elmir ([email protected]) Exception handling 29  Handling an exception  Handling multiple exceptions If there are multiple types of errors and exceptions to catch, you must define a separate catch block for each type of event. When referring to exception type, it means "an exception that is of the type of the exception class or one of its subclasses". Therefore, in the sequential order of catch clauses, an exception type should not come after an exception type of a superclass. It's crucial to pay attention to the order of the catch clauses so that more specific exceptions (subclasses) are handled before more general exceptions. Failure to do so may result in a compiler error message. Dr. Youssef Elmir ([email protected]) Exception handling 30  Handling an exception  Handling multiple exceptions public class TestException2 { public static void main(String[] args) { // Insert code to start the application here. int i = Integer.parseInt( args ); int j = Integer.parseInt( args ); try { System. out.println("result = " + (i/j)); } inaccessible catch (Exception e) { Catch block } catch ( ArithmeticException e) { System. out.println ("Division by zero"); }}} Dr. Youssef Elmir ([email protected]) Exception handling 31  Handling an exception  The Finally block We have observed that an exception interrupts the execution of a method and redirects it to the appropriate catch block. However, we can include a block of instructions that will always execute, regardless of whether an exception is thrown or not. This block of instructions is placed  either after the try block if it executed without any exceptions,  or after the catch block if an exception was caught. Dr. Youssef Elmir ([email protected]) Exception handling 32  Handling an exception  The Finally block This block is introduced by the "finally" keyword and must be placed after the last catch block. try {..... } catch (Ex e) {..... } finally { // instructions } Notes: Statements in the finally block are often used to perform "cleanup" (or resource release) actions, such as closing a file or a network connection. Dr. Youssef Elmir ([email protected]) Exception handling 33 THROWING AN EXCEPTION Dr. Youssef Elmir ([email protected]) Exception handling 34  Throwing an exception  Using throws The keyword “throws“  Any method that may throw a checked exception must either have a try/catch block (if it handles the exception locally) or declare the exception using the "throws" keyword (if the exception is propagated to be handled by another method).  We have already learned how to use the try/catch block, now let's explore the usage of "throws". Dr. Youssef Elmir ([email protected]) Exception handling 35  Throwing an exception  Using throws The keyword “throws”  Example public class TestThrows { public void test(String[] a) throws ArithmeticException { int i = Integer.parseInt(a); int j = Integer.parseInt(a); System.out.println("result = " + (i/j)); } … } Dr. Youssef Elmir ([email protected]) Exception handling 36  Throwing an exception If an exception occurs  Using throws here, it will not be handled locally. The keyword “throws” Instead, it will propagate upwards  Example through the execution public class TestThrows { stack, searching for a public void test(String[] a) throws piece of code capable of ArithmeticException handling it. This { process is often likened int i = Integer.parseInt(a); to a "bubble" moving int j = Integer.parseInt(a); up through the stack. System.out.println("result = " + (i/j)); } … } Dr. Youssef Elmir ([email protected]) Exception handling 37  Throwing an exception  Using throws The keyword “throws”  The method itself determines the exceptions it may throw. It can throw exceptions from JDK-provided exception classes or from new exception classes created by the programmer, which may be better suited to the specific needs of the method.  When throwing an exception in a method using the `throw` keyword, it must be declared in the method signature using the `throws` keyword. Dr. Youssef Elmir ([email protected]) Exception handling 38  Throwing an exception  Using throws The keyword “throws”  example public class TestThrow { public void test(String[] a) throws ArithmeticException { int i = Integer.parseInt(a); int j = Integer.parseInt(a); if(j==0) throw new ArithmeticException(); System.out.println ("result = " + (i/j)); } } Dr. Youssef Elmir ([email protected]) Exception handling 39  Throwing an exception  Using throws Custom exceptions  If needed, you can create custom exceptions by subclassing the Exception class. By convention, it's common to include the word "Exception" in the name of the new subclass.  Then, simply use the `throw` keyword followed by an instance of the custom exception class. Dr. Youssef Elmir ([email protected]) Exception handling 40  Throwing an exception  Using throws Custom exceptions  Example Suppose we want to work with points that have non-negative coordinates. In this case, we can create a Point class with a constructor that takes two arguments representing the coordinates. Inside this constructor, we can check the validity of the coordinates provided by the user. If any of the coordinates are incorrect (i.e., negative), we can throw an exception using the `throw` keyword. Dr. Youssef Elmir ([email protected]) Exception handling 41  Throwing an exception  Using throws Custom exceptions  Example The `throw` statement requires an object of the type of the exception we want to raise. To achieve this, we'll create a class called CoordinatesException that inherits from the Exception class. class CoordinatesException extends Exception { } Dr. Youssef Elmir ([email protected]) Exception handling 42  Throwing an exception  Using throws Custom exceptions  Example class Point { private int x; private int y; public Point( int x, int y) throws CoordinatesException { if((x