1 Features of Java (2) CS 3331 Sections 4.5 and 4.6.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Yoshi
CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
CS102--Object Oriented Programming
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
Exception Handling Xiaoliang Wang, Darren Freeman, George Blank.
CS 2430 Day 22. Announcements Prog4 test document and Rational Junit tests are due this Friday at 2 PM Quiz 3 this Friday Quiz 4 next Friday Exam 2: 4/3/13.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
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.
For use of Cleveland State's IST410 Students only 1 Exception.
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
Java Exceptions. Types of exceptions  Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
PACKAGES. PACKAGES IN JAVA A package is a collection of related classes and interfaces in Java Packages help in logical grouping of classes and interfaces.
Objectives Understanding what an exception is Understanding the heirarchy of exception classes Learn the types of exception and how to catch and handle.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions 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 in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
06 - Exceptions. 2 ©S. Uchitel, 2004 A familiar sight? Bluescreen.scr.
Java Review 2 – Errors, Exceptions, Debugging Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Introduction to Java Chapter 11 Error Handling. Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle.
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.
CS203 Java Object Oriented Programming Errors and Exception Handling.
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
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.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
COMP Exception Handling Yi Hong June 10, 2015.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
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.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
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.
MIT AITI 2004 – Lecture 14 Exceptions Handling Errors with Exceptions.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Today’s lecture Review of chapter 8 Go over examples.
SourceAnatomy1 Java Source Anatomy Barb Ericson Georgia Institute of Technology July 2008.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
David Evans CS201j: Engineering Software University of Virginia Computer Science Lecture 10: Programming Exceptionally.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
OOP Tirgul 7. What We’ll Be Seeing Today  Packages  Exceptions  Ex4 2.
Tirgul 13 Exceptions 1.
Exceptions, Interfaces & Generics
Introduction to OO Program Design
CS102 – Exceptions David Davenport Latest: May 2015
ATS Application Programming: Java Programming
Java Programming Language
Exception Handling and Reading / Writing Files
Exception Handling in Java
Joel Adams and Jeremy Frens Calvin College
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.
Tutorial MutliThreading.
Java Basics Exception Handling.
Exception Handling.
Presentation transcript:

1 Features of Java (2) CS 3331 Sections 4.5 and 4.6

2 Outline  Package  Exception

3 Organizing Java Programs  Java provides mechanisms to organize large-scale programs in logical and maintainable fashion. Class: highly cohesive functionalities; unit of encapsulation. File: one or more closely related classes; unit of compilation. Package: a collection of related classes or packages.

4 Package Declaration  Use package statements to declare package for classes and interfaces, e.g., // File: Homework1.java package cs3331; public class Homework1 { /* … */ } // File: MyProject.java package cs3331.proj1; public interface MyProject { /* … */ } The package statement must be the first statement. Q: What if the package statement is missing?

5 Package Declaration (Cont.)  Use all lowercase letters for package names  Use reverse domain names if plan to publish widely, e.g., package edu.utep.cs.cs3331;

6 Example - JDK Packages  JDK library classes are organized into a number of packages: java.awt: GUI java.io: I/O java.util: utilities java.applet: applet java.net: networking javax.swing: GUI The package java is reserved for JFC.

7 Referring to Classes from Other Packages  Use fully qualified names, e.g., public class MyApplet extends java.applet.Applet { private java.util.List figures = new java.util.LinkedList(); // … } Q: Why figures’s type List rather than LinkedList?

8 Referring to Classes (Cont.)  Use import statements, e.g., import java.applet.Applet; import java.util.*; public class MyApplet extends Applet { private List figures = new LinkedList(); // … } Q: Multiple import statements? JDK packages first and user-defined in the alphabetical order. Q: Static import?

9 Avoiding Conflicts  What if two packages contain classes with the same name? What will happen? // both java.awt and java.util have List import java.awt.*; import java.util.*; public class MyList extends List { /* … */} Q: Why such a conflict can happen?

10 Avoiding Conflicts (Cont.)  Use fully qualified names, or  Import specific class to have a precedence, e.g., import java.awt.List; import java.awt.*; import java.util.*; public class MyList extends List { /* … */ }

11 How Are Packages Located?  Packages are mapped to directories, e.g. // Suppose classes proj1.part1.A and proj2.B. public class Test { proj1.part1.A x; proj2.B y; } Java tools (e.g., javac and java) try to find A in the directory./proj1/part1 and B from./proj2 (assuming that. is in CLASSPATH).

12 Outline Package  Exception

13 Exceptions  An exception is an unexpected condition in programs, e.g., division by zero, null pointer, array index out of bound, etc.  A mechanism to recover from unexpected conditions or failures (i.e., exceptions) is called an exception handling mechanism.

14 Why Exception Handling?  Location difference  Separate flows of control for normal and exceptional public Object pop() throws StackEmptyException { if (isEmpty()) { throw new StackEmptyException(); } // pop and return the top element of this stack... }

15 Exception Handling (Cont.) // Client code Stack jobStack = new Stack(); // … try { Job work = (Job) jobStack.pop(); // normal flow of control, e.g., work.doIt(); } catch (StackEmptyException e) { // exceptional flow of control … e.printStackTrace(); } normal flow exceptional flow

16 Exception Hierarchy Exceptions are modeled as objects of exception classes. Exception classes are organized in a class hierarchy, called an exception hierarchy. Throwable Error RuntimeException Exception JVM errors JVM exceptions user exceptions JVM exceptions Unchecked Exception Checked Exception

17 Unchecked vs. Checked  Unchecked exceptions Exceptions that need not be handled or recovered Errors and runtime exceptions  Checked exceptions Exceptions that need be addressed, i.e., caught or declared in the throws clause All others except for errors and runtime exceptions

18 Example - Unchecked public void doSomething(Object x) { String str = x.toString(); // NullPointerException // … }

19 Example - Checked // Incorrect code public void readFile(String n) { // can throw java.io.FileNotFoundException FileInputStream f = new FileInputStream(n); // … } // Correct code: propagate exceptions public void readFile(String n) throws java.io.FileNotFoundException { FileInputStream f = new FileInputStream(n); // … }

20 Example - Checked (Cont.) // Correct code: catch and handle exceptions public void readFile(String n) { try { FileOutputStream f = new FileOutputStream(n); // … } catch (FileNotFoundException e) { e.printStackTrace(); System.exit(-1); }

21 Defining Your Own Exceptions  Same as defining regular classes public class StackEmptyException extends Exception { public StackEmptyException() { } public StackEmptyException(String msg) { super(msg); } // other fields and methods here … }

22 Throwing Exceptions  Use the throw statement public class Stack { /** Pops and returns the top element of this stack. */ public Object pop() throws StackEmptyException { if (isEmpty()) { throw new StackEmptyException(“Sorry, stack is empty.”); } // the rest of code … } // other fields and methods here … } Q: Why need the throws clause?

23 Handling Exceptions  Use the try-catch-[finally] statement Stack jobs = …; try { // normal case … Job work = (Job) jobs.pop(); work.doIt(); } catch (StackEmptyException e) { // handle exceptions fireMe(); } finally { // finalization goVacation(); } Can have multiple catch clauses.

24 Exercise  What is wrong with the definition of the class YourClass. Fix it. public void doMyJob(int x) throws IllegalArgumentException, MyException { // … } MyException java.lang.Exception doMyJob() MyClass public class YourClass { public void doYourJob(int x) { new MyClass().doMyJob(x); }