1 Why do we need exceptions? In C, return variables must be used to indicate errors: if((fd = fopen(path,...)) == -1){ if(errno==a){...} else if(errno==b){...}

Slides:



Advertisements
Similar presentations
Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Advertisements

Yoshi
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
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.
Designing an ADT The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT What data does.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
For use of Cleveland State's IST410 Students only 1 Exception.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
Java Exceptions. Types of exceptions  Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot.
CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 CPSC150 Exceptions When things.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
1 From Yesterday private = accessible only to the class that declares it public = accessible to any class at all protected = accessible to the class and.
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.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
Java Exception Handling ● Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions: – Examples:
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
12.1 Exceptions The limitations of traditional methods of exception handling Error conditions are a certainty in programming Programmers make.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
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.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
Preventing and Correcting Errors
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
June 14, 2001Exception Handling in Java1 Richard S. Huntrods June 14, 2001 University of Calgary.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
CIS 270—Application Development II Chapter 13—Exception Handling.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
CC1007NI: Further Programming Week 8-9 Dhruba Sen Module Leader (Islington College)
Exceptions 1. Your computer takes exception Exceptions are errors in the logic of a program (run-time errors). Examples: Exception in thread “main” java.io.FileNotFoundException:
Exception Handling. Outline What is an Exception How to use exceptions catch ing throw ing Extending the Exception class Declaring using the throws clause.
CS 2511 Fall  Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:  Examples: Out.
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 in JAVA. Introduction Exception is an abnormal condition that arises when executing a program. In the languages that do not support.
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.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
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.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Exception. Agenda Exception. Handling Exceptions. The finally Clause.
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.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
1 ָ נן oop uException-Handling Mechanism – similar to C++ l throw e signals the occurrence of an exception lThe statement try/catch allows the calling.
Exceptions in the Java programming language J. W. Rider.
Object Throwable ErrorException RuntimeException.
Java Exceptions a quick review….
Creating and Modifying Text part 2
ATS Application Programming: Java Programming
Exception Handling in Java
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.
Tutorial Exceptions Handling.
Chapter 12 Exception Handling and Text IO Part 1
Why do we need exceptions?
Exception Handling.
Exceptions and Exception Handling
Presentation transcript:

1 Why do we need exceptions? In C, return variables must be used to indicate errors: if((fd = fopen(path,...)) == -1){ if(errno==a){...} else if(errno==b){...} // other error code } // do something

2 Why do we need exceptions? What are the problems with this? –This complicates the code by adding extra clutter to check the value of the return arguments. –If you have a function f() that calls g() that calls h(), and h() needs to return an error, both g() and f() have to contain special code to handle the exception

3 Why do we need exceptions? How does the code change when we add exceptions? try{ fd = new FileReader(path,...); } catch(IOException e){ // error code } catch(FileNotFoundException e){ // error code } // do something

4 When should exceptions be used? Exceptions provide a way to signal errors without having to use return variables They should generally be used when an unexpected error occurs For example, Java uses an exception to signal when a file you are trying to open could not be found. However, when searching for an item in an array, Java returns a -1 if it cannot find the item.

5 Checked Exceptions You can either use one of the existing exceptions, or create your own Most exceptions extend Exception, but a function can throw any class that extends Throwable Such exceptions are known as checked exceptions –Functions that throw a checked exception must advertise this by using the throws keyword –Every function that calls a function that can throw an exception must either use a try…catch block or advertise that it throws the Exception with a throws keyword

6 Unchecked Exceptions Unchecked exceptions do not need to be caught by your program. There are two types: –Exceptions that extend Error are serious virtual machine errors, like OutOfMemoryError –Exceptions that extend RuntimeException can be caught, but do not need to be. These are problems like NullPointerException and IndexOutOfBoundsException

7 Using Exceptions In order to signal an error has occurred, your code must throw an exception: throw new MyException(“Error Message”) Also, all functions that throw exceptions must specifically state that they throw exceptions. A function that throws MyException and MyOtherException would be defined as follows: int myFunction() throws MyException, MyOtherException

8 Using Exceptions A function that calls a function that can throw an exception must deal with it in one of two ways: –Advertise that it throws the exception –Use a try…catch block

9 Using Exceptions try{ fd = new FileReader(path,...); } catch(IOException e){ // error code } catch(Exception e){ // error code }

10 Exceptions and Inheritance When creating a subclass, do not change the exceptions thrown by a method you override, unless you are changing them to a subclass of the previous exception. However, you can remove one or more of the exceptions from the throws keyword. –If a method throws MyException and MyOtherException, a method that overrides it can throw only MyException

11 Finally… When working with resources such as files or network connections, special handling is required for exceptions. Resources often need to be properly closed to ensure that normal behavior continues, regardless of whether an exception will be thrown or not.

12 Why Finally? import java.io.*; class ProcessFile{ public static void main(String[] args){ if(args.length > 0){ FileReader f; try{ // Open a file: f = new FileReader(args[0]); SomeOtherClass.process(f); f.close(); } catch (IOException x){ System.out.println(x); if (f != null) f.close(); }}}}

13 Why Finally? import java.io.*; class ProcessFile{ public static void main(String[] args){ if(args.length > 0){ FileReader f; try{ // Open a file: f = new FileReader(args[0]); SomeOtherClass.process(f); } catch(IOException x){ System.out.println(x); } finally{ if(f != null) f.close(); }}}

14 SaM and Exceptions Why do you need to know this? In Part 2, your compiler will not have to throw exceptions. However, you will be required to use SaMTokenizer SamTokenizer can throw an exception when you request a token

15 SamTokenizer and Exceptions public int getInt() throws TokenizerException { if(next() == StreamTokenizer.TT_NUMBER) return (int)tokens.nval; else throw new TokenizerException("Attempt to read non-numerical value as an integer", lineNo()); }

16 Exceptions in your Project All methods that use SamTokenizer, and any methods that call those methods, must advertise that they throw TokenizerException. This will allow you to avoid handling the exceptions. Under normal conditions, you should never get have a TokenizerException thrown, since you can check the type of the next token using peekAtKind()