Introduction Exception handling Exception Handles errors

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Yoshi
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
COMP 121 Week 5: Exceptions and Exception Handling.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
When you use an input or output file that does not exist, what will happen? −The compiler insists that we tell it what the program should do in such case.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
06 - Exceptions. 2 ©S. Uchitel, 2004 A familiar sight? Bluescreen.scr.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
COMP Exception Handling Yi Hong June 10, 2015.
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Practice Session 9 Exchanger CyclicBarrier Exceptions.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
EXCEPTIONS There's an exception to every rule.. 2 Introduction: Methods  The signature of a method includes  access control modifier  return type 
MIT AITI 2004 – Lecture 14 Exceptions Handling Errors with Exceptions.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
Java Exceptions a quick review….
Exceptions In this lecture:
Chapter 10 – Exception Handling
Tirgul 13 Exceptions 1.
MIT AITI 2003 Lecture14 Exceptions
Introduction to Exceptions in Java
Exceptions, Interfaces & Generics
Introduction to Exceptions in Java
Introduction to OO Program Design
CSE 501N Fall ’09 17: Exception Handling
Exceptions 10-Nov-18.
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
Exception Handling Chapter 9.
ATS Application Programming: Java Programming
Exception Handling and Reading / Writing Files
Exception Handling Chapter 9 Edited by JJ.
Exception Handling.
Web Design & Development Lecture 7
Java Exception Very slightly modified from K.P. Chow
Exception Handling in Java
Java Exception Very slightly modified from K.P. Chow
CSE 143 Java Exceptions 1/18/2019.
Managing Errors and Exceptions
Java Exceptions Dan Fleck CS211.
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Tutorial Exceptions Handling.
Chapter 12 Exception Handling and Text IO Part 1
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
Tutorial MutliThreading.
Exceptions 10-May-19.
Exceptions References: Jacquie Barker, Beginning Java Objects; Rick Mercer, Computing Fundamentals With Java; Wirfs-Brock et. al., Martin Fowler, OOPSLA.
Java Basics Exception Handling.
Exception Handling and Event Handling
Exception Handling.
Java Programming: From Problem Analysis to Program Design, 4e
Presentation transcript:

Introduction Exception handling Exception Handles errors Indication of problem during execution E.g., array out of bounds Handles errors Class Exception

Program throws an Exception and fails Example public static int average(int[] a) { int total = 0; for(int i = 0; i < a.length; i++) { total += a[i]; }return total / a.length; } What happens when this method is used to take the average of an array of length zero? Program throws an Exception and fails java.lang.ArithmeticException: division by zero

What is an Exception? An error event that disrupts the program flow and may cause a program to fail. Some examples: Performing illegal arithmetic operations Illegal arguments to methods Accessing an out-of-bounds array element Hardware failures Writing to a read-only file …

Another Example Output: public class ExceptionExample { public static void main(String args[]) { String[] greek = {"Alpha","Beta"}; System.out.println(greek[2]); } Output: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at ExceptionExample.main(ExceptionExample.java:4)

Exception message format Example [exception class]: [additional description of exception] at [class].[method]([file]:[line number]) Example java.lang.ArrayIndexOutOfBoundsException: 2 at ExceptionExample.main(ExceptionExample.java:4) What exception class? Which array index is out of bounds? What method throws the exception? What file contains the method? What line of the file throws the exception?

Use a try-catch block to handle exceptions that are thrown try { Exception Handling Use a try-catch block to handle exceptions that are thrown try { // code that might throw exception } catch ([Type of Exception] e) { // what to do if exception is thrown

Exception Handling Example public static int average(int[] a) { int total = 0; for(int i = 0; i < a.length; i++) total += a[i]; return total / a.length; } public static void printAverage(int[] a) { try { int avg = average(a); System.out.println("the average is: " + avg); catch(ArithmeticException e) { System.out.println("error calculating average");

Catching Multiple Exceptions Handle multiple possible exceptions by multiple successive catch blocks try { // code that might throw multiple exception } catch (IOException e) { // handle IOException and all subclasses catch (ClassNotFoundException e2) { // handle ClassNotFoundException

Exception Terminology When an exception happens we say it was thrown or raised When an exception is dealt with, we say the exception is was handled or caught

Unchecked Exceptions All the exceptions we've seen so far have been Unchecked Exceptions (RuntimeException, Error, and their subclasses) Usually occur because of programming errors, when code is not robust enough to prevent them They are numerous and can sometimes be ignored by the programmer in the method signature methods are not obliged to handle unchecked exceptions

There are also Checked Exceptions Usually occur because of errors programmer cannot control, e.g., hardware failures, unreadable files They are less frequent and they cannot be ignored by the programmer . . .

Dealing with Checked Exceptions Every method must catch (handle) checked exceptions or specify that it may throw them (using the throws keyword) void readFile(String filename) { try { FileReader reader = new FileReader("myfile.txt"); // read from file . . . } catch(FileNotFoundException e){ System.out.println("file was not found"); } or void readFile(String filename) throws FileNotFoundException{

Exception Hierarchy All exceptions are instances of classes that are subclasses of Exception

Checked vs. Unchecked Exceptions Not subclass of RuntimeException Subclass of RuntimeException if not caught, method must specify it to be thrown if not caught, method may specify it to be thrown for errors that the programmer cannot directly prevent from occurring For errors that the programmer can directly prevent from occurring IOException, FileNotFoundException, SocketException, etc. NullPointerException, IllegalArgumentException, IllegalStateException, etc.

Checked vs. Unchecked Exceptions Unchecked exceptions are exceptions that can be avoided in your code (asking the user to re-enter a value, using if statements) --usually the result of a programming error Checked are harder to avoid because they usually don’t have anything to do with your code, so we need to be more careful with them.

Constructing Exceptions Exceptions have at least two constructors: no arguments NullPointerException e = new NullPointerException() single String argument, descriptive message that appears when exception error message is printed IllegalArgumentExceptione e =new IllegalArgumentException("number must be positive");

Designing your Own Exception Types To write your own exception, write a subclass of Exception and write both types of constructors public class MyCheckedException extends IOException{ public MyCheckedException() {} public MyCheckedException(String m) { super(m); } public class MyUncheckedException extends RuntimeException{ public MyUncheckedException() {} public MyUncheckedException(String m) { Note that not necessarily a direct subclass

Throw exception with the throw keyword Throwing Exceptions Throw exception with the throw keyword public static int average(int[] a) { if (a.length == 0) { throw new IllegalArgumentException("array is empty"); } int total = 0; for(int i = 0; i < a.length; i++){ total += a[i]; return total / a.length;

or try { int[] myInts= {}; System.out.println(avg(myInts)); System.out.println(“Java is fun”); } catch (IllegalArgumentException e) { System.out.println(“array is empty”); or System.out.println(e.getMessage());

Keyword Summary Four new Java keywords Try and catch : used to handle exceptions that may be thrown throws: to specify which exceptions a method throws in method declaration throw: to throw an exception

Summary of Java Exception Handling A method detects an error and throws an exception Exception handler processes the error The error is considered caught and handled in this model Code that could generate errors put in try blocks Code for error handling enclosed in a catch block Keyword throws tells exceptions of a method