Exceptions. Lecture 15 CGS 3416 Fall November 23, 2015

Similar documents
CS 111 Classes I 1. Software Organization View to this point:

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

JAVA - EXCEPTIONS. An exception can occur for many different reasons, below given are some scenarios where exception occurs.

What are exceptions? Bad things happen occasionally

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

Software Construction

Lecture J - Exceptions

CS506 Web Design and Development Solved Online Quiz No. 01

D06 PROGRAMMING with JAVA

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

I. INTRODUCTION. International Journal of Computer Science Trends and Technology (IJCST) Volume 3 Issue 2, Mar-Apr 2015

Topics in Software Reliability

Fundamentals of Java Programming

Java Programming Language

RMI Client Application Programming Interface

The Interface Concept

1. Properties of Transactions

Dennis Olsson. Tuesday 31 July

Classes Dennis Olsson

Exception Handling In Web Development DevelopIntelligence LLC

public static void main(string args[]) { System.out.println( "f(0)=" + f(0));

Using Files as Input/Output in Java 5.0 Applications

An Exception Monitoring System for Java

Specialized Programme on Web Application Development using Open Source Tools

Java from a C perspective. Plan

No no-argument constructor. No default constructor found

AP Computer Science Java Subset

Java Application Developer Certificate Program Competencies

The first time through running an Ad Hoc query or Stored Procedure, SQL Server will go through each of the following steps.

COMMUNITY COLLEGE OF CITY UNIVERSITY CITY UNIVERSITY OF HONG KONG

Smallest Java Package? Java.applet.* having 1 class and 3 interfaces. Applet Class and AppletContext, AppletStub, Audioclip interfaces.

16.1 DataFlavor DataFlavor Methods. Variables

JAVA INTERVIEW QUESTIONS

Java SE 8 Programming

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Teach Yourself Java in 21 Minutes

CSE 1020 Introduction to Computer Science I A sample nal exam

Master of Sciences in Informatics Engineering Programming Paradigms 2005/2006. Final Examination. January 24 th, 2006

C# and Other Languages

Try-Catch FAQ. Version February InterSystems Corporation 1 Memorial Drive Cambridge MA

core. Volume I - Fundamentals Seventh Edition Sun Microsystems Press A Prentice Hall Title ULB Darmstadt

Specialized Programme on Web Application Development using Open Source Tools

public static void main(string[] args) { System.out.println("hello, world"); } }

Application Programming Interface

Java Fundamental Classes Reference

Event-Driven Programming

On the (un)suitability of Java to be the first programming language

13 File Output and Input

Lab Experience 17. Programming Language Translation

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

Zebra and MapReduce. Table of contents. 1 Overview Hadoop MapReduce APIs Zebra MapReduce APIs Zebra MapReduce Examples...

Java Interview Questions and Answers

Konzepte objektorientierter Programmierung

Managing Android Fragmentation. Carter Jernigan two forty four a.m. LLC

Chapter 1 Fundamentals of Java Programming

All rights reserved. Copyright in this document is owned by Sun Microsystems, Inc.

Copyright. Restricted Rights Legend. Trademarks or Service Marks. Copyright 2003 BEA Systems, Inc. All Rights Reserved.

Software Engineering Techniques

Mail User Agent Project

CSE 326: Data Structures. Java Generics & JUnit. Section notes, 4/10/08 slides by Hal Perkins

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

Object-Oriented Programming in Java

WRITING DATA TO A BINARY FILE

Cucumber: Finishing the Example. CSCI 5828: Foundations of Software Engineering Lecture 23 04/09/2012

Langages Orientés Objet Java

Lecture 1 Introduction to Android

Secure Mobile Agent Systems Using Java: Where are We Heading?

Crash Course in Java

The ConTract Model. Helmut Wächter, Andreas Reuter. November 9, 1999

Explain the relationship between a class and an object. Which is general and which is specific?

Simple Java I/O. Streams

Programmation 2. Introduction à la programmation Java

Programming and Software Development (PSD)

Java Coding Practices for Improved Application Performance

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Java Card Application Programming Interface

Java Interfaces. Recall: A List Interface. Another Java Interface Example. Interface Notes. Why an interface construct? Interfaces & Java Types

Introduction to Programming System Design. CSCI 455x (4 Units)

Chapter 5 Names, Bindings, Type Checking, and Scopes

AP Computer Science File Input with Scanner

FILE I/O IN JAVA. Prof. Chris Jermaine Prof. Scott Rixner

JCrasher: an automatic robustness tester for Java

Unit Testing JUnit and Clover

7 Mutating Object State

CIS 190: C/C++ Programming. Polymorphism

Introduction to Objective-C. Kevin Cathey

What you need to use this book. Summary of Contents. To run the samples in this book you will need:

Java (12 Weeks) Introduction to Java Programming Language

C++ INTERVIEW QUESTIONS

IMDB Data Set Topics: Parsing Input using Scanner class. Atul Prakash

Monitors and Exceptions : How to Implement Java efficiently. Andreas Krall and Mark Probst Technische Universitaet Wien

Evaluation of AgitarOne

LAB4 Making Classes and Objects

3 Improving the Crab more sophisticated programming

ARIZONA CTE CAREER PREPARATION STANDARDS & MEASUREMENT CRITERIA SOFTWARE DEVELOPMENT,

Creating a Simple, Multithreaded Chat System with Java

Robustness Testing of the Microsoft Win32 API

Why Do Developers Neglect Exception Handling?

Question R11.3. R11.3 How do you open a file whose name contains a backslash, like c:\temp\output.dat?

Transcription:

Exceptions Lecture 15 CGS 3416 Fall 2015 November 23, 2015

What is an Exception? An exception is an object that represents an error or exceptional event that has occurred. These events are usually errors that occur because the run-time environment has detected an operation that is impossible to carry out. Exception objects are all children of the Throwable class. Exceptions represent normal error events that can occur in your program. Examples: Array index out of bounds - IndexOutOfBoundsException Open a file that does not exist - FileNotFoundException Call a method that does not exist - NoSuchMethodException

Types of Exceptions Exceptions generally come in two flavors: Normal Exceptions (checked exceptions) These exceptions are the ones that every good program should watch for (for example, the FileNotFoundException. You have to handle these (either catch them or declare that your method can throw them). Runtime Exceptions (unchecked exceptions) These exceptions have the potential to be in all code you write (example - IndexOutOfBoundsException). You do not need to handle these. Errors There is a class of exceptions called errors these are usually not recoverable (example - VirtualMachineError). These exceptions do not need to be handled.

Some Common Built-In Exception Types ClassNotFoundException - raised if you attempt to use a nonexistent class. CloneNotSupportedException - raised on an attempt to call clone() for an object that doesn t implement the Cloneable interface. RunTimeException - numerous types of programming errors that usually cause the program to abort. ArithmeticException NullPointerException IndexOutOfBoundsException others IOException - raised on input/output errors. Several subtypes. AWTException - raised to deal with graphics errors. You can also build your own exception types. These should be derived from class Exception, or from one of its subclasses.

Why have exceptions? Exceptions are used to build robust programs. Exceptions allow the programmer to recover from an error or exceptional event. Usually, if an exception is not handled, it can cause the program to terminate unnaturally and prematurely. Java was originally a language for embedded systems (TVs, phones, watches, etc.) These systems should never stop working, exceptions are needed for these systems.

How do you do exception handling? The process involves: Claiming exceptions - each method needs to specify what exceptions it expects might occur Throwing an exception - When an error situation occurs that fits an exception situation, an exception object is created and thrown. Catching an exception - Exception handlers (blocks of code) are created to handle the different expected exception types. The appropriate handler catches the thrown exception and performs the code in the block.

Claiming Exceptions In a method, to claim an exception, use the keyword throws and list the exceptions that may occur in the method. Examples: public void mymethod() throws IOException public void yourmethod() throws IOException, AWTException, BobException

Throwing Exceptions Use the keyword throw, along with the type of exception being thrown. An exception is an object, so it must be created with the new operator. Examples: throw new BadHairDayException(); MyException m = new MyException(); throw m; if (persononphone!= bubba) throw new Exception("Stranger on the phone!!"); Notice that this is different than the keyword throws, which is used in claiming exceptions.

Catching Exceptions Any group of statements that can throw and exception, or a group of statements that you want to watch for Runtime or Error exceptions, must be within a try block. At the end of the try block there must be either a catch or a finally block. A catch block has a parameter that is the type of exception this catch block will handle. There can be several catch blocks for a try block. If an exception is thrown then the first catch block that that has a parameter matching the exception s type will be the one that catches the exception. A finally block is ALWAYS executed no matter how control leaves a try block. This will happen even if a return statement is executed in the try block, and even if control passes to a catch block.

Example try { IO code opening and reading from/to files } catch (FileNotFoundException) { tell the user and probably repeat try block } catch (IOException) { blanket catch for all other IO problems } finally { make sure to close any files that might be open }

What happens if an exception is not caught? If your method does not catch a checked exception and does not declare that your method can throw it then the compiler will complain. If your method throws an exception, then the method that called your method must handle the exception or declare that it can throw that exception. If no method handles the exception then the program crashes and a message is printed out describing the exception. The same happens if an unchecked exception should occur. The only difference between a checked an unchecked exception is that checked exceptions must be handled.

Rethrowing exceptions Writing code to handle exceptions is tedious and often you have no idea what to do for error recovery. It is sometimes easier just to re-throw the checked exception as an unchecked exception. Example: catch (Exception e) { throw new RuntimeException(e); }

When to use exceptions? Exceptions are not appropriate for all error-checking tasks. Exceptions are good for situations in which the error doesn t need to be handled in the same block where it occurred. Conventional error-checking is better for simple tests. For example, validating user input falls into this category it s best to test user input values with simple if-statements and loops. Exceptions are good for handling errors that would result in termination of the program, otherwise.

Instance methods in exception objects Exception objects are created from classes, which can have instance methods. There are some special instance methods that all exception objects have (inherited from Throwable): public String getmessage() returns a detailed message about the exception. public String tostring() returns a short message describing the exception. public String getlocalizedmessage() public void printstacktrace()