Java Exceptions 10/18/2011 1

Similar documents
Java CPD (I) Frans Coenen Department of Computer Science

CS170 Lab 11 Abstract Data Types & Objects

AP Computer Science Java Subset

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

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

AP Computer Science Static Methods, Strings, User Input

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

J a v a Quiz (Unit 3, Test 0 Practice)

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

Basics of Java Programming Input and the Scanner class

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

Introduction to Object-Oriented Programming

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

Lecture J - Exceptions

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

Remote Method Invocation

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:

Exceptions and their interpretation

Java Programming Language

Konzepte objektorientierter Programmierung

Java Interview Questions and Answers

Teach Yourself Java in 21 Minutes

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

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

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

What are exceptions? Bad things happen occasionally

Java: overview by example

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Licensed for viewing only. Printing is prohibited. For hard copies, please purchase from

CPLEX Tutorial Handout

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

Remote Method Invocation in JAVA

Basic Object-Oriented Programming in Java

CS506 Web Design and Development Solved Online Quiz No. 01

Coding Standard for Java

Building a Multi-Threaded Web Server

OBJECT ORIENTED PROGRAMMING LANGUAGE

Inside the Java Virtual Machine

Transparent Redirection of Network Sockets 1

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

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

JAVA - METHODS. Method definition consists of a method header and a method body. The same is shown below:

CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5

Basic Java Syntax. Program Structure

Contents. 9-1 Copyright (c) N. Afshartous

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

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

Massachusetts Institute of Technology 6.005: Elements of Software Construction Fall 2011 Quiz 2 November 21, 2011 SOLUTIONS.

5.2 Q2 The control variable of a counter-controlled loop should be declared as: a.int. b.float. c.double. d.any of the above. ANS: a. int.

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

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

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

Programming Languages CIS 443

Creating a Simple, Multithreaded Chat System with Java

AP Computer Science Java Mr. Clausen Program 9A, 9B

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

Chapter 1 Java Program Design and Development

Crash Course in Java

C++ INTERVIEW QUESTIONS

Sample CSE8A midterm Multiple Choice (circle one)

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

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

Application Development with TCP/IP. Brian S. Mitchell Drexel University

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

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

Introduction to Computer Programming, Spring Term 2014 Practice Assignment 3 Discussion

Homework/Program #5 Solutions

Java from a C perspective. Plan

CMSC 202H. ArrayList, Multidimensional Arrays

CS 121 Intro to Programming:Java - Lecture 11 Announcements

LAB4 Making Classes and Objects

B.Sc (Honours) - Software Development

Fundamentals of Java Programming

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

Part I. Multiple Choice Questions (2 points each):

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

Compile and Runtime Errors in Java

The Interface Concept

Using Two-Dimensional Arrays

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Appendix A Using the Java Compiler

Manual For Using the NetBeans IDE

Grundlæggende Programmering IT-C, Forår Model solutions to. Written exam in Introductory Programming

Chapter 2 Introduction to Java programming

Tutorial: Getting Started

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

JAVA - INHERITANCE. extends is the keyword used to inherit the properties of a class. Below given is the syntax of extends keyword.

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

Copyright Descriptor Systems, Course materials may not be reproduced in whole or in part without prior written consent of Joel Barnum

Java Program Coding Standards Programming for Information Technology

API Document Webaroo Technology India Pvt. Ltd.

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

Software Construction

AVRO - SERIALIZATION

16. Recursion. COMP 110 Prasun Dewan 1. Developing a Recursive Solution

Approach of Unit testing with the help of JUnit

Security Module: SQL Injection

Graduate Assessment Test (Sample)

JAVA - MULTITHREADING

Transcription:

Java Exceptions 10/18/2011 1

Overview An exception is an unusual circumstance, such as an error condition, that must be handled in a non-standard way. Java and many other languages (including C++), exceptions serve as a standard mechanism for handling execution error conditions. Provides for handling unusual cases at the appropriate level(s). For example, an airplane could have a stuck wing flap detected in a very low-level method monitoring a wing flap's position. No ability to communicate information directly to the pilot. A wing flap exception can be reported upward to the higher levels that call the low-level method where the exception is detected. The higher level layers, with broader status information, could automatically adjust other control surfaces and report the wing flap exception to the pilot. 10/18/2011 2

A Little Demo public class Test { public static void main(string[] args) { System.out.println(5/0); javac Test.java java Test Exception in thread "main" java.lang.arithmeticexception: / by zero at Test.main(Test.java:3) 10/18/2011 3

Exception Example public class Test { public static void main(string[] args) { try { System.out.println( 5 / 0); catch (ArithmeticException a) { System.out.println("You're dividing by zero!"); This will catch and handle any ArithmeticException. Other exceptions will still get the language system s default behavior. javac Test.java java Test You're dividing by zero! 10/18/2011 4

Exception Mechanism The exception mechanism consists of three parts: 1. definition of the exception class 2. throwing the exception when exceptional condition is detected 3. catching or handling the exception (try and catch). 10/18/2011 5

Exercise 1A - List line numbers executed and output 1. System.out.print("1"); 2. try { 3. System.out.print("2"); 4. if (true) throw new Exception(); 5. System.out.print("3"); 6. 7. catch (Exception e) { 8. System.out.print("4"); 9. 10. finally { 11. System.out.print("5"); 12. 13. System.out.println("6"); 10/18/2011 6

Exercise 1B - List line numbers executed and output 1. public class Exercise1 { 2. static void f1() { 3. System.out.print("1"); 4. try { 5. System.out.print("2"); 6. f2(); 7. System.out.print("3"); 8. 9. catch (Exception e) { System.out.print("4"); 10. finally { System.out.print("5"); 11. System.out.println("6"); 12. 13. static void f2 () throws Exception { 14. if (true) throw new Exception(); 15. 16. public static void main(string s[]) { f1(); 17.

Exercise 1C - List line numbers executed and output 1. public class Exercise1 { 2. static void f1() throws Exception { 3. System.out.print("1"); 4. try { 5. System.out.print("2"); 6. f2(); 7. System.out.print("3"); 8. 9. catch (Exception e) { System.out.print("4"); throw e; 10. finally { System.out.print("5"); 11. System.out.println("6"); 12. 13. static void f2 () throws Exception { 14. if (true) throw new Exception(); 15. 1245 Exception thread "main" java.lang.exception at Exercise1.f2(Exercise1.java:15) at Exercise1.f1(Exercise1.java:6) at Exercise1.main(Exercise1.java:19) 16. public static void main(string s[]) throws Exception { 17. f1(); 18. 19.

Define Generally, an exception class inherits from the parent class Exception. The exception class definition minimally defines a class constructor but may also provide methods for analysis of the conditions causing the exception. The following is a typical class definition for counterexception with a constructor that copies a string message complaint presumably detailing the cause of the exception. An example of the constructor's use illustrates a new counterexception created with the complaint that count failed. 10/18/2011 9

Define and Use Example Define class counterexception extends Exception { String complaint; public counterexception(string complaint){ this.complaint = complaint; public String tostring(){ return "counter Exception " + complaint; Use new counterexception("count failed."); 10/18/2011 10

Throw When an error condition is detected, it is necessary to handle it immediately where detected or throw the exception to the calling method. Exception handling is a mechanism for transferring control from where an error occurred to where it can be handled most appropriately. After the exception is thrown, the throwing method terminates and execution control is immediately passed backward along the chain of callers from where the exception was thrown. Any method along the calling chain can: a) handle the exception and continue with execution, b) handle the exception and again throw the exception to the calling method to handle c) or do nothing, terminate immediately and let the calling method deal with the exception. The down method below is an example of throwing an exception, in this case when the counter n becomes negative. 10/18/2011 11

Throw Example public int down() throws counterexception { if (n <= 0) throw new counterexception( n + " count Down failed."); return --n; The down method is an example of throwing an exception, in this case when the counter n becomes negative. If exception is thrown, execution does not reach return --n; 10/18/2011 12

Catch Handling an exception consists of trying a method that throws an exception and catching a thrown exception. Catching an exception prevents the exception from being passed to a higher level calling method. If an exception is not caught, the method terminates immediately and control is passed to the higher level calling method so that it might catch the exception. Consider the following example which causes a counterexception to be thrown by method down when the counter becomes negative. The try and catch go together to define the method that throws the exception, down, and the exception to be caught, counterexception. Only if an exception is thrown will it be caught and the catch statement(s) executed. Any statements following the catch would be executed as normal. 10/18/2011 13

Catch Example Catch try { acounter.down( ); catch (counterexception ce) { System.out.println("" + ce); Throw public int down() throws counterexception { if (n <= 0) throw new counterexception( n + " count Down failed."); return --n; 10/18/2011 14

Throwing exceptions to caller When an exception is not handled in a method it must be thrown to the higher level calling method. That method must state that it throws an exception as throws counterexception. The down method listed earlier does not handle or catch the counterexception thrown so the exception is thrown back to the calling method, action. The direct effect of down throwing an exception is to terminate its execution, passing execution to the catch, so that the remaining statements of down (i.e. return --n) are not executed. public int down() throws counterexception { if (n <= 0) throw new counterexception( n + " count Down failed."); return --n;

Finally try Invokes a method that throws an exception. catch Point of execution of exception throw. finally - Always executed at end of a try block. 10/18/2011 16

Exception Class Example 1. class counterexception extends Exception { // Define 2. String complaint; 3. public counterexception(string c) { 4. this.complaint = c; 5. 6. public String tostring( ) { 7. return "counter Exception + complaint; 8. 9. 10.class counter { 11. int n = 0; 12. public int zero() { return n=0; 13. public int up() { return ++n; 14. public int down() throws counterexception { // Throw 15. if (n <= 0) 16. throw new counterexception 17. (n + " count Down failed."); 18. return --n; 19. 20. 10/18/2011 17

Exception Class Use Example 21.public class Example { 22. public static void main( String args[] ) { 23. counter acounter = new counter( ); 24. acounter.zero( ); 25. acounter.up(); 26. try { acounter.down( ); 27. catch (counterexception ce) { // Catch 28. System.out.println("" + ce); 29. 30. try { acounter.down( ); 31. catch (counterexception ce) { // Catch 32. System.out.println("" + ce); 33. 34. finally { 35. System.out.println( Finally ); 36. 37. 38.

Exercise 2 1. class counterexception extends Exception { 2. String complaint; 3. public counterexception(string c){ this.complaint = c; 4. public String tostring( ) { return "counter Exception + complaint; 5. 1. List the sequence of line numbers executed and output. 6. class counter { 7. int n = 0; 8. public int zero() { return n=0; 9. public int up() { return ++n; 10. public int down() throws counterexception { 11. if (n <= 0) throw new counterexception (n + " count Down failed."); 12. return --n; 13. 14. 2. The catch is defined in main method but is executed by the throw. Is the catch visible to the throw? 3. What does the throw and catch resemble? 15. public class Example { 16. public static void main( String args[] ) { 17. counter acounter = new counter( ); 18. acounter.zero( ); 19. acounter.up(); 20. try { acounter.down( ); 21. catch (counterexception ce) { System.out.println("" + ce); 22. try { acounter.down( ); 23. catch (counterexception ce) { System.out.println("" + ce); 24. finally { System.out.println( Finally ); 25. 26.

Exercise 2 Continued 4. List the sequence of line numbers executed and output. 5. What occurs at Line 21? 1. class counterexception extends Exception { 2. String complaint; 3. public counterexception(string c){ this.complaint = c; 4. public String tostring( ) { return "counter Exception + complaint; 5. 6. class counter { 7. int n = 0; 8. public int zero() { return n=0; 9. public int up() { return ++n; 10. public int down() throws counterexception { 11. if (n <= 0) throw new counterexception (n + " count Down failed."); 12. return --n; 13. 14. 15. public class Example { 16. public static void main( String args[] ) throws Exception { 17. counter acounter = new counter( ); 18. acounter.zero( ); 19. acounter.up(); 20. acounter.down( ); 21. acounter.down( ); 22. System.out.println( Completed ); 23. 24.