Lecture J - Exceptions

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

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

D06 PROGRAMMING with JAVA

Java Programming Language

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.

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

Creating a Simple, Multithreaded Chat System with Java

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

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

Java from a C perspective. Plan

Software Construction

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

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

Exceptions and their interpretation

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

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

Fundamentals of Java Programming

CS 121 Intro to Programming:Java - Lecture 11 Announcements

Using Two-Dimensional Arrays

Course Intro Instructor Intro Java Intro, Continued

15-214: Principles of Software Construction 8 th March 2012

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

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

Crash Course in Java

Event-Driven Programming

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

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

Using Files as Input/Output in Java 5.0 Applications

13 File Output and Input

Application Programming Interface

WRITING DATA TO A BINARY FILE

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

The Interface Concept

C++ INTERVIEW QUESTIONS

INPUT AND OUTPUT STREAMS

public void creditaccount(string accountnumber, float amount) { this.accounts.get(accountnumber).credit(amount); }

Object-Oriented Programming in Java

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

3 Pillars of Object-oriented Programming. Industrial Programming Systems Programming & Scripting. Extending the Example.

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Continuous Integration Part 2

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Java Network. Slides prepared by : Farzana Rahman

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Division of Informatics, University of Edinburgh

Konzepte objektorientierter Programmierung

CS506 Web Design and Development Solved Online Quiz No. 01

Homework/Program #5 Solutions

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Building a Multi-Threaded Web Server

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

CMSC 202H. ArrayList, Multidimensional Arrays

Consuming a Web Service(SOAP and RESTful) in Java. Cheat Sheet For Consuming Services in Java

AVRO - SERIALIZATION

core 2 Basic Java Syntax

D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

Mail User Agent Project

TABLE OF CONTENTS...2 INTRODUCTION...3 APPLETS AND APPLICATIONS...3 JAVABEANS...4 EXCEPTION HANDLING...5 JAVA DATABASE CONNECTIVITY (JDBC)...

AP Computer Science File Input with Scanner

Chapter 2 Introduction to Java programming

Moving from CS 61A Scheme to CS 61B Java

Java Application Developer Certificate Program Competencies

LAB4 Making Classes and Objects

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

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

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

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Introduction: Abstract Data Types and Java Review

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

Software Development with UML and Java 2 SDJ I2, Spring 2010

CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5

Manual. Programmer's Guide for Java API

Outline. Computer Science 331. Stack ADT. Definition of a Stack ADT. Stacks. Parenthesis Matching. Mike Jacobson

OBJECT ORIENTED PROGRAMMING LANGUAGE

HW3: Programming with stacks

Lesson: All About Sockets

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

AP Computer Science Java Subset

An Overview of Java. overview-1

Java Interview Questions and Answers

Polymorphism. Why use polymorphism Upcast revisited (and downcast) Static and dynamic type Dynamic binding. Polymorphism.

Oracle WebLogic Server

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

D06 PROGRAMMING with JAVA

Chapter 1 Java Program Design and Development

Introduction to Java

Teach Yourself Java in 21 Minutes

Evaluation. Copy. Evaluation Copy. Chapter 7: Using JDBC with Spring. 1) A Simpler Approach ) The JdbcTemplate. Class...

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Java Classes. GEEN163 Introduction to Computer Programming

Stacks. Stacks (and Queues) Stacks. q Stack: what is it? q ADT. q Applications. q Implementation(s) CSCU9A3 1

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

Java: overview by example

Transcription:

Lecture J - Exceptions Slide 1 of 107.

Exceptions in Java Java uses the notion of exception for 3 related (but different) purposes: Errors: an internal Java implementation error was discovered E.g: out of memory Runtime exceptions: a programming logic error was discovered E.g. division by 0 Checked Exceptions: an exceptional case was discovered E.g. file not found Errors and Runtime exceptions will usually cause the program to crash Checked exceptions should usually be handled by the programmer Slide 2 of 107.

Occurrence of a runtime exception public class ExceptionExample { public static void main(string[] args) { int[] a = {2, 4, 6, 8; for(int j = 0; j <= a.length ; j++) System.out.println(a[j]); Slide 3 of 107.

Program Crash due to a runtime exception Slide 4 of 107.

Runtime exceptions in the Java API java.lang.arithmeticexception java.lang.nullpointerexception java.lang.illegalargumentexception java.lang.negativearraysizeexception java.lang.arrayindexoutofboundsexception java.lang.classcastexception Slide 5 of 107.

Throwing a runtime exception public class Clock { private int hours, minutes, seconds; // constructors and methods public void settime(int h, int m, int s){ if (h <1 h>12 m <0 m>59 s<0 s>59) throw new IllegalArgumentException(); hours = h; minutes = m; seconds = s; Slide 6 of 107.

Declaring a new runtime exception public class StackUnderflowException extends RuntimeException { public class Stack { int elements[]; int top;//next empty location in the elements array // constructor, push(), isempty() public int pop() { if (isempty()) throw new StackUnderflowException(); return elements[--top]; The RuntimeException class has an empty constructor and one that accepts a string (denoting an error message). Slide 7 of 107.

Checked Exceptions Checked Exceptions denote exceptional situations that need to be dealt with. They are dealt with by catching them Using the try { catch { statement Their possible occurrence in a method is considered part of the interface of the method Must be declared using the throws keyword Checked exceptions in the Java API: java.net.connectexception java.io.ioexception java.io.eofexception java.io.filenotfoundexception java.util.toomanylistenersexception Slide 8 of 107.

Catching Exceptions import java.io.*; public class FirstLine { public static void main(string[] args){ String name = args[0]; try { BufferedReader file = new BufferedReader(new FileReader(name)); String line = file.readline(); System.out.println(line); catch (IOException e) { System.out.println( Problem: + e); Slide 9 of 107.

Throwing Checked Exceptions public class OverDraftException extends Exception { public class BankAccount { private float balance; // constructors, fields, and methods public void withdraw(float amount) throws OverDraftException { if (amount > balance) throw new OverDraftException(); balance -= amount; Slide 10 of 107.

Exception life-cycle When a program performs an illegal operation the following happens: The regular flow of the program stops An exception object is created, which encapsulates the information about the problem that occurred The method may try to catch and handle the exceptional situation If the method ignores the exception the method execution ceases. An exception then appears at the place in which the method was called If the exception is not handled anywhere, the program crashes. Slide 11 of 107.

Pumping up an exception public static void main(string[] args) { try { dowithdraws(); catch (OverDraftException e) { callmanager(); Overdraft! private static dowithdraws() throws OverDraftException { // Get list of withdraw orders for(/* iterate over withdraw orders */) bankaccount.withdraw(amount) I ll crash the method! Hey, no one Catches this Slide 12 of 107.

Declaring for exceptions If a method must declare all the non run-time exceptions it may throw. The declaration is done using the throws keyword The user of the method is warned against possible exceptions that this method can throw The exceptions that might be thrown by a method should also be documented with the @exception tag. Slide 13 of 107.

Documenting Exceptions /** * Creates a Gate of a given type * @param type The type of the required gate * @return A Gate of the required type * @exception UnknownGateException If type doesn t * refer to a familiar gate. */ public Gate makegate(string type) throws UnkownGateException { if (type.equals( OR )) return new OrGate(); if (type.equals( AND )) return new AndGate(); if (type.equals( NOT )) return new NotGate(); throw new UnknownGateException(); Slide 14 of 107.

Either catch // Called when the user chooses to add a gate private useraddsgate() { String type = //... look up the selected gate type try { Gate gate = makegate(type); //... adds the gate to the model //... catch (UnknownGateException uge) { // ignore this, don t add the gate Slide 15 of 107.

or declare // Called when the user chooses to add a gate private useraddsgate() throws UnknownGateException { String type = Gate gate = makegate(type); //... look up gate type //... adds the gate to the model //... Slide 16 of 107.

Exceptions Hierarchy All the classes for indicating run-time errors are derived from the class java.lang.throwable. The object you deliver to the throw statement must be an instance of class Throwable The constructor of class Throwable initializes all the information about the location where the exception occurred, the state of the run-time stack etc. In this way this information is set for every exception object. The following diagram explains the inheritance hierarchy for exceptions. Slide 17 of 107.

Throwable class hierarchy Throwable Error Exception RuntimeException Slide 18 of 107.

Multiple Catches import java.io.*; public class FirstLine { public static void main(string[] args){ String name = args[0]; try { BufferedReader file = new BufferedReader(new FileReader(name)); String line = file.readline(); System.out.println(line); catch (FileNotFoundException e) { System.out.println( File not found: + name); catch (IOException e) { System.out.println( Problem: + e); Slide 19 of 107.

finally After all catches in a try-catch block, a finally clause may appear. The finally section of code is executed before exiting from the try-block, whether or not an exception occurred. The finally section is executed even if the try-catch block was exited by a return or break statement. try { // acquire resources // do stuff catch (E1 e) { catch (E2 e) { finally { // release resources Slide 20 of 107.