Why do we need exceptions?

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

Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
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.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
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){...}
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.
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]);
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
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 }
Exception Handling in JAVA. Introduction Exception is an abnormal condition that arises when executing a program. In the languages that do not support.
1 Exception handling in Java Reading for this lecture: Weiss, Section 2.5 (exception handling), p. 47. ProgramLive, chapter 10. I need to know whether.
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.
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.
Object Throwable ErrorException RuntimeException.
Java Exceptions a quick review….
Chapter 10 – Exception Handling
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
Tirgul 13 Exceptions 1.
MIT AITI 2003 Lecture14 Exceptions
Introduction to Exceptions in Java
Introduction Exception handling Exception Handles errors
Creating and Modifying Text part 2
CSE 501N Fall ’09 17: Exception Handling
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
Handling Exceptions.
Advanced Programming Behnam Hatami Fall 2017.
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.
Chapter 11—Exceptions Handling Exceptions Throwing Exceptions.
ATS Application Programming: Java Programming
Exception Handling in Java
Exception Handling and Reading / Writing Files
Web Design & Development Lecture 7
Chapter 12: Exceptions and Advanced File I/O
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.
Tutorial Exceptions Handling.
Chapter 12 Exception Handling and Text IO Part 1
Exception Handling Contents
Tutorial MutliThreading.
Exceptions 10-May-19.
Java Basics Exception Handling.
Exception Objects An exception is an abnormal condition that arises in a code sequence at rum time. Exception is a way of signaling serious problem.
Exception Handling.
Lab 1 Exception Handling.
Exceptions and Exception Handling
Presentation transcript:

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

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

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){ // do something

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.

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 Also mention about default constructors

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

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

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

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

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

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.

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) }}}}

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(); }}}

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

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()); }

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()