CS 251 Intermediate Programming Exceptions

Similar documents
CS159. Nathan Sprague

Programming II (CS300)

Data Structures. 02 Exception Handling

Programming II (CS300)

PIC 20A Exceptions. Ernest Ryu UCLA Mathematics. Last edited: November 27, 2017

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

CS159. Nathan Sprague

09/08/2017 CS2530 INTERMEDIATE COMPUTING 9/8/2017 FALL 2017 MICHAEL J. HOLMES UNIVERSITY OF NORTHERN IOWA TODAY S TOPIC: Exceptions and enumerations.

Sri Vidya College of Engineering & Technology Question Bank

CS61B Lecture #12. Today: Various odds and ends in support of abstraction.

Exceptions. Examples of code which shows the syntax and all that

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

EXCEPTION HANDLING. Summer 2018

CS 3 Introduction to Software Engineering. 3: Exceptions

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.

2.6 Error, exception and event handling

To Think About. MyClass.mogrify(new int[] { 1, 2, 4, 6 }));

Exceptions and Design

Exceptions in Java

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling

Exception-Handling Overview

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun

CS 11 java track: lecture 3

What is the purpose of exceptions and exception handling? Vocabulary: throw/raise and catch/handle Exception propagation Java checked and unchecked

CS 251 Intermediate Programming Inheritance

Correctness and Robustness

CS 251 Intermediate Programming Methods and Classes

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Topic 6: Exceptions. Exceptions are a Java mechanism for dealing with errors & unusual situations

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

Answer Key. 1. General Understanding (10 points) think before you decide.

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Comp 249 Programming Methodology Chapter 9 Exception Handling

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University

17. Handling Runtime Problems

BBM 102 Introduction to Programming II Spring Exceptions

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES

Object Oriented Programming

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

Recreation. MyClass.mogrify(new int[] { 1, 2, 4, 6 }));

Introduction to Java. Handout-3a. cs402 - Spring

CS 251 Intermediate Programming Methods and More

COE318 Lecture Notes Week 10 (Nov 7, 2011)

BBM 102 Introduction to Programming II Spring 2017

Exercise Session Week 8

Pages and 68 in [JN] conventions for using exceptions in Java. Chapter 8 in [EJ] guidelines for more effective use of exceptions.

Exceptions. What exceptional things might our programs run in to?

Chair of Software Engineering. Java and C# in Depth. Prof. Dr. Bertrand Meyer. Exercise Session 8. Nadia Polikarpova

Exceptions. CSC207 Winter 2017

Fundamentals of Object Oriented Programming

Exception in thread "main" java.lang.arithmeticexception: / by zero at DefaultExceptionHandling.main(DefaultExceptionHandling.

Chapter 13 Exception Handling

ECE 122. Engineering Problem Solving with Java

COS226 - Spring 2018 Class Meeting # 21 April 23, 2018

Unit III Rupali Sherekar 2017

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

16-Dec-10. Consider the following method:

Exceptions and Libraries

Exception Handling. Chapter 9

Exercise Session Week 8

Chapter 4 Defining Classes I

Std 12 Lesson-10 Exception Handling in Java ( 1

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

School of Informatics, University of Edinburgh

COMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions

CMSC131. Exceptions and Exception Handling. When things go "wrong" in a program, what should happen.

Exceptions. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

Assertions and Exceptions Lecture 11 Fall 2005

Lecture 14: Exceptions 10:00 AM, Feb 26, 2018

CS S-22 Exceptions 1. Running a web server, don t want one piece of bad data to bring the whole thing down

CS 351 Design of Large Programs Threads and Concurrency

Introduction to Computation and Problem Solving. Class 25: Error Handling in Java. Prof. Steven R. Lerman and Dr. V. Judson Harward.

COMP 202 Java in one week

6.Introducing Classes 9. Exceptions

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

Exception Handling in C++

Introduction to Software Design

Errors and Exceptions

Programming Languages and Techniques (CIS120)

C16b: Exception Handling

Typecasts and Dynamic Dispatch. Dynamic dispatch

COMP1008 Exceptions. Runtime Error

Laboratorio di Tecnologie dell'informazione

Java. Error, Exception, and Event Handling. Error, exception and event handling. Error and exception handling in Java

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

CS61B Lecture #12. Programming Contest: Coming up Saturday 5 October. See the contest announcement page, here.

About This Lecture. Outline. Handling Unusual Situations. Reacting to errors. Exceptions

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters.

EMBEDDED SYSTEMS PROGRAMMING OO Basics

Defensive Programming

Exceptions. Produced by. Algorithms. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology

CSE 331 Software Design & Implementation

COMP200 EXCEPTIONS. OOP using Java, based on slides by Shayan Javed

Transcription:

CS 251 Intermediate Programming Exceptions Brooke Chenoweth University of New Mexico Fall 2018

Expecting the Unexpected Most of the time our programs behave well, however sometimes unexpected things happen. Java s way of handling these types of problems is called exception handling

When do exceptions occur? When you least expect them to... When there s something wrong with the hardware, or other things that you can t control from your program. Input from files (or other streams) Communication of various kinds (internet, users) Or... When you create them yourself

What is an exception? Like everything else in java, they are Objects Objects can be created and customized, extended and inherited Many exceptions are already predefined in java ArrayIndexOutOfBoundsException is one of them Belongs to the class RuntimeException For more refer to the Exception class in the Java API.

Your own exception class public class Di vide ByZe roexc epti on extends RuntimeException { public Di vide ByZe roexc epti on () { super (" Zero division detected "); public Di vide ByZe roexc epti on ( String msg ) { super ( msg ); Just an example! Java already has an ArithmeticException for this.

Creating an exception Create a new exception object: Exception myex = new Divi deby Zero Excep tion (); Creating an exception, doesn t mean you caused an exceptional event. Nothing happens until you throw it...

Exception keywords try clause for testing potential exception code. catch catching the exceptions, if they happen throws used in method headers to indicate method might cause exception throw used by a method to throw (cause) an exception finally code executed after the try-catch clauses, regardless of whether exception happened or not.

Catching an Exception Try to compile the following: public class Sleeper { public void sleep10secs () { Thread. sleep (10000); Will not work... Why?

Methods throwing Exceptions Methods can define that they wish to be able to throw one or more exceptions int mymethod() throws SomeException int mymethod() throws SomeException, SomeOtherException Note that these exception classes must exist and be defined as the prior DivideByZeroException for the program to compile Thread.sleep() is defined like this, it throws an InterruptedException in case its sleep is disturbed.

Catching exceptions Calls to methods that potentially throw exceptions must be padded to allow compilation, to allow for the exception to happen There are two basic approaches: Ignoring the exceptions, and passing them on to the caller of your method. Catching the exception and dealing with it yourself

Ignoring (passing on) exceptions To avoid dealing with the exceptions yourself, while still calling methods that might throw exceptions - your method must also be declared to throw those same exceptions. public class Sleeper { public void sleep10secs () throws InterruptedException { Thread. sleep (10000); Only viable if caller is prepared to handle exceptions

Catching exceptions Other solution: catch the exception and handle it yourself public class Sleeper { public void sleep10secs () { try { Thread. sleep (10000); catch ( InterruptedException ie ) { System. out. println ( " Woke up early!" ); When you do this, make sure you really handle the exception.

Don t eat exceptions! try { bigredbutton. pushit (); catch ( EndOfTheWorldException ex) { // Silently ignoring Armageddon... At the very least, add some debugging output in case the impossible exception happens.

Which one to use? Both above methods are allowed Only use passing on when you are sure that caller can handle exception, or if ok to ignore exceptions If you can handle exception within then do! Makes your program more robust

Throwing an exception If necessary, you can create and throw an exception: throw new SomeException("Explanation"); Assumes the SomeException class exists, and has a constructor taking a String argument Aborts the execution of the current method, no return value is provided Exception must be handled by the caller of your method Your method must be declared as: public int mymethod() throws SomeException

Throwing while catching Can throw an exception in a catch clause, if you want to create your own Exception messages, or provide an abstraction for the real exception: try { Thread. sleep (10000); catch ( InterruptedException ie ) { throw new SomeException (" Awakened "); The class SomeException must exist

try...catch...finally Similar to an if statement Can have only one try clause, but... Any number of catch clauses Catch clauses should be ordered in decreasing order of specialization, i.e., if catch (Exception e) is the first, it will catch all exceptions. finally clause to be used if something must happen, even if exception will be thrown (and method exit)

try/catch/finally example try { driver. getincar (); driver. drivetowork (); catch ( DeadBatteryExceptio n ex) { driver. callaaa (); catch ( NoKeysException ex) { driver. takebus (); finally { if( driver. isincar ()) { driver. getoutofcar ();

A note on usage... Many types of problems can be detected and prevented inside your code. When possible this is preferred since exceptions run slower than normal code. Exception code is executed in special mode, and exiting by normal means is faster in high-performance requirements Good article: http://www.javaworld.com/javaworld/ jw-08-2000/jw-0818-exceptions.html