Full Transcript

CST8132 Object Oriented Programming Exception Handling Professor: James Mwangi PhD. Computer Engineering Technology - Computing Science Jan 15, 2024 Email: mwangij@alg...

CST8132 Object Oriented Programming Exception Handling Professor: James Mwangi PhD. Computer Engineering Technology - Computing Science Jan 15, 2024 Email: [email protected] School of ICT: CETCS / AP Welcome to Java OOP James Mwangi PhD. Professor, Computer Engineering Technology – Computer Science [email protected] Exception handling Use try…catch…finally for this code int[] a = new int; a = 9; 3 Warm up Question: 2 minutes: 1. What is the name of the supertype of all errors and exceptions in Java language? 2. Do a quick 2-minute search and type the answer on the meeting chat. 3. A bonus mark for the first correct answer 4 Objectives – Week 9 Exceptions ✓ What is an exception? ✓ Types of Exceptions: checked vs. unchecked The superclass of all errors and Exception handling exceptions in Java language ✓How to handle exceptions in Java Throwable ✓Try…Catch…Finally 5 Some project ideas Lab 5 – Store Management System III with exception handling, test plan, javadoc Test Plan – template provided Only one Scanner object for the project Exception Handling 6 Final modifier With variable – becomes constant With method – cannot be overridden in subclasses With class – cannot be sub-classed Eclipse demo 7 Exceptions In life, we have to plan for events that we hope will never be needs: Insurance Smoke detectors First aid training Police … 8 Exceptions When we write software, sometimes problems happen that we didn’t plan for. Object wasn’t initialized File doesn’t exist Array index out of range … 9 Exceptions Same thing when we write software, sometimes problems happen that you didn’t plan. Object wasn’t initialized - NullPointerException File doesn’t exist - IOException Array index out of range - ArrayIndexOutOfBoundsException … We call these exceptions 10 Exceptions Hierarchy in Java 11 Exceptions Exception is-a Throwable “conditions that a reasonable application might want to catch” Programmer error Error is-a Throwable “serious problems that a reasonable application should not try to catch” System error RuntimeException is-a Exception unchecked exceptions - “exceptions that can be thrown during the normal operation of the Java Virtual Machine” that do not need to be handled. If an Exception is not a RuntimeException, then it is a checked exception and it must be handled. 12 Today’s Agenda Examples of Checked Exemptions - need to handle these Examples of Unchecked Exceptions - no need to handle these ArithmeticException IOException (java.io package) IndexOutOfBoundsException EOFException ArrayIndexOutOfBoundsException FileNotFoundException StringIndexOutOfBoundsException EmptyStackException InvalidClassException NoSuchElementException ClassNotFoundException (java.lang package) MissingResourceException NoSuchMethodException IllegalArgumentException 13 Exception Handling TRY…CATCH…FINALLY 14 finally block always executes when the try block exits Exceptions (Try-Catch) Try block –Specify Requirement syntax learn more here Catch block syntax Finally block syntax finally block always executes when the try block exits 15 Termination Model of Exception Handling After the exception is handled, program control does not return to the throw point, because the try block has expired (and its local variables have been lost). Control resumes after the last catch block. 16 Try block vs try statement Try block is just the block of code within the curly braces of try Try statement includes try block, catch blocks and/or finally block 17 Exceptions (Try-catch-finally) 18 finally block will execute whether or not an exception is thrown will execute even if a try block exits by using a return, break or continue statement Typically used to release resources A situation where finally block will not execute: System.exit calls 19 Exceptions (Try with resources) The try-with-resources statement ensures that each resource is closed at the end of the statement. 20 Exceptions - Throw You can throw a better error message: 21 Exceptions - throws Sometimes you don’t want handle the Exception in the current method. In that case you declare that the methods throws the Exception. 22 Throw vs thows throw throws Used to throw an exception for a Used to indicate what exception types method may be thrown by a method Cannot throw multiple exceptions Can declare multiple exceptions throw is followed by an object throws is followed by a class (new type) Ex: throws ArithmeticException Ex: throw new ArithmeticException(“message”) Used inside the method Used with the method signature 23 Checked vs Unchecked Exceptions Checked typically caused by conditions that are not under the control of the program Compiler enforces special requirements (will see this in file handling) Unchecked All exception types that are direct or indirect subclasses of RuntimeException Examples – ArrayIndexOutOfBoundsExceptions, ArithmeticExceptions, NullPointerException etc Avoidable by bulletproofing your code 24 Exceptions Catch should be as close to the problem as possible Place catch blocks from the specific to general A catch block can rethrow an Exception Reuse existing exception classes where possible, but you can create new ones if needed. Only the first matching catch executes 25 Summary 26 What is an Exception? Any strange event that can potentially make a program to fail. An event occurring during program execution that can potentially disrupt the normal flow of instructions. Use TRY…CATCH…FINALLY to handle exceptions 27 Java Exceptions Hierarchy Throwable: supertype of all exceptions and errors in Java. Three subclasses of Throwable: 1. Error: system errors. Base class for all errors in java. we do not catch errors e.g. OutOfMemoryError is irrecoverable. 2. Exception: base class for all exceptions in Java. programmers throw and catch exceptions which are subclasses of Exception 3. RuntimeException: a runtime programming error – we don’t throw and catch these. E.g. NullPointerException 28 Java Exceptions Hierarchy Source: javamex Source: codejava. 29 Book reading Deitel & Deitel Chapter 7 Page 270-273 Introduction Professional programmers endeavor to Write bug-free programs that don’t crash, are able to gracefully handle any condition and recover from unusual situations. That said, errors may still occur if programmers an unanticipated situation occurs or if a software if not sufficiently tested. It is important to handle those strange situations that can make a program to fail 30 Questions 31 Activity 1 - Bonus for the first correct program Take the code provided on the chat by the professor. add a meaningful try block to the code. public class ExceptionWithBonus { public static void main(String[] args) { //declare variables int x = 7, y = 0; //do some calculation int z = x / y; } } 32 Activity 2 add a catch block to Activity 1 code handle ArithmeticException Your updated code is to display error full exception message. Run the code. 33 Activity 2 add a finally block to Activity 2 code that prints the message ‘Bad math, Stop dividing by zero!’ Run your code and show it to the professor. 34 Bye Next Topic File I/O

Use Quizgecko on...
Browser
Browser