1. Trang chủ
  2. » Giáo Dục - Đào Tạo

Bài giảng điện tử môn tin học: Developing Comprehensive Projects pps

114 453 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 114
Dung lượng 2,33 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Throwing Exceptions, cont Control is passed up the execution stack to a matching handler  Various methods exist for processing exceptions:  getMessage  toString class name + messa

Trang 1

Part IV: Developing Comprehensive

Trang 2

Chapter 10 Exception Handling

 What exceptions are for

 What exceptions are NOT for

 Catching & Throwing exceptions

 Exception Specifications

 Standard Java Exceptions

 Exceptions and Polymorphism

Trang 3

What Exceptions are For

 To handle Bad Things

 I/O errors, other runtime errors

 when a function fails to fulfill its

specification

 so you can restore program stability (or exit gracefully)

Trang 4

What Exceptions are For, cont

 To force you to handle Bad Things

 because return codes can be tedious

 and sometimes you’re lazy

Trang 5

Example File I/O

public FileReader( String fileName)

throws FileNotFoundException

public void close() throws IOException

Trang 7

What Exceptions are For, cont

 To signal errors from constructors

 because constructors have no return value

Trang 8

What Exceptions are NOT For

 NOT For Alternate Returns:

 e.g., when end-of-file is reached:

while ((s = f.readLine()) != null) …

 Exceptions are only for the exceptional!

Trang 9

Catching Exceptions

 Wrap code to be checked in a try-block

 checking occurs all the way down the

execution stack

 try-blocks can be nested

 control resumes at most enclosed matching handler

Trang 10

Catching Exceptions, cont

 Place one or more catch-clauses after

try-block

 runtime system looks back up the call stack for a matching handler

 subclass types match superclass types

 catching Exception catches everything (almost)

 handlers are checked in the order they

appear

Trang 11

Throwing Exceptions

 Must throw objects derived (ultimately) from

Throwable

 Usually derive from java.lang.Exception

 The class name is the most important

attribute of an exception

 Can optionally include a message

 Provide two constructors:

 MyException( )

Trang 12

Throwing Exceptions, cont

 Control is passed up the execution

stack to a matching handler

 Various methods exist for processing exceptions:

 getMessage( )

 toString( ) (class name + message)

printStackTrace( )

Trang 13

Throwing Exceptions, cont

 Functions must “advertise” their

exceptions

 every function must specify the “checked” exceptions it (or its callees!) may throw

 Callers must do one of two things:

 handle your exceptions with try-catch, or

 advertise your exceptions along with theirs

Trang 14

Sample Program

 FixedStack

 implements a stack with an array of Object

 various methods throw exceptions

 class StackException

 StackTest

 must handle StackExceptions

Trang 15

class StackException extends Exception {

Trang 16

class FixedStack

{

private int capacity;

private int size;

private Object[] data;

public FixedStack(int cap)

Trang 17

public Object pop()

Trang 21

Standard Java Exceptions

Throwable

Trang 22

Class java.lang.Exception

 The one you usually derive from

 “Checked Exceptions”

 specifications checked at compile time

 you must either catch or advertise these

 Used for recoverable errors

 Not programmer errors

Trang 24

Class java.lang.Error

 For JVM Failures and other Weird Things

 let program terminate

InternalError is one of these

 Don’t catch them

 you don’t know what to do!

Trang 26

Class java.lang.RuntimeException

 Stupid Name!

 Same as logic_error in C++

 Program logic errors

 e.g., bad cast, using a null handle, array index violation, etc.

 Shouldn’t happen!

 fixed during testing

 Similar in spirit to C’s assert( ) macro

Trang 28

 “Use checked exceptions for

recoverable conditions and run-time exceptions for programming errors” (Bloch, Effective Java )

Trang 30

class StackException extends RuntimeException

Trang 31

Exceptions and Inheritance

~ Subclass Overrides ~

 Methods overridden in subclasses must maintain the parent method’s contract

 substitutability

 cannot add exceptions to specification

 can omit, however

 can throw subclasses of parent’s

exceptions

Trang 32

// Relaxing the Exception Specification

Trang 33

// Throwing a Subclass Exception

class MyException extends Exception {}

class AnotherException extends MyException {}

class Parent {

public void f() throws MyException

{}

}

class Child extends Parent {

public void f() throws AnotherException

Trang 35

The finally Clause

 For code that must ALWAYS run

 No matter what!

Even if a return or break occurs first

 Placed after handlers (if they exist)

 try-block must either have a handler or a finally-block

Trang 37

public static void main(String[] args)

Trang 39

Managing Resources

 Other than memory

 files, connections, etc.

 Need to deallocate, even if exceptions occur

Trang 41

public static void main(String[] args) {

Trang 42

Program Output

 If no file name given (args.length == 0):

java.lang.ArrayIndexOutOfBoundsException: 0

 If file doesn’t exist:

java.io.FileNotFoundException: <file name>

 If file opened successfully:

Trang 43

When to Handle Exceptions

Note: Manage.f( ) didn’t catch

anything

 wouldn’t know what to do if it did!

 You often let exceptions pass up the call stack

 Or you can re-throw in a catch

throw x; // in a handler where x was

Trang 44

 Don’t catch & ignore

 catch (Exception x){} // disables

Trang 45

How Exceptions Work

 When an exception is thrown execution

backtracks up the runtime stack (list of active function invocations)

 Each stack frame contains information

regarding local handlers, if any

 Otherwise, execution returns up to the next caller, looking for a suitable catch

 What happens if there isn’t a matching catch?

Trang 46

Uncaught Exceptions

 What if there is no handler for an exception?

 The thread dies!

 exceptions belong to a thread specific)

Trang 47

(stack-Chapter 11: Multithreading

 Multiple tasks for computer

 Draw & display images on screen

 Check keyboard & mouse input

 Send & receive data on network

 Read & write files to disk

 Perform useful computation (editor, browser, game)

 How does computer do everything at once?

Trang 48

Multitasking (Time-Sharing)

 Approach

 Computer does some work on a task

 Computer then quickly switch to next task

 Tasks managed by operating system (scheduler)

 Computer seems to work on tasks

concurrently

 Can improve performance by reducing waiting

Trang 49

Multitasking Can Aid Performance

 Single task

 Two tasks

Trang 50

Multiprocessing (Multithreading)

 Approach

 Multiple processing units ( multiprocessor )

 Computer works on several tasks in parallel

 Performance can be improved

Trang 51

Perform Multiple Tasks

Using…

 Process

 Definition – executable program loaded in

memory

 Has own address space

 Variables & data structures (in memory)

 Each process may execute a different program

 Communicate via operating system, files, network

 May contain multiple threads

Trang 52

Perform Multiple Tasks

Using…

 Thread

 Definition – sequentially executed stream of

instructions

 Shares address space with other threads

 Has own execution context

 Program counter, call stack (local variables)

 Communicate via shared access to data

Trang 53

Motivation for Multithreading

 Captures logical structure of problem

 May have concurrent interacting components

 Can handle each component using separate thread

 Simplifies programming for problem

 Example

Trang 54

Motivation for Multithreading

 Better utilize hardware resources

 When a thread is delayed, compute other threads

 Given extra hardware, compute threads in parallel

 Reduce overall execution time

 Example

Trang 56

Programming with Threads

Trang 57

Creating Threads in Java

 You have to specify the work you want the thread to do

 Define a class that implements the Runnable

interface

public interface Runnable { public void run();

}

 Put the work in the run method

 Create an instance of the worker class and create a

Trang 58

Thread Class

public class Thread {

public Thread(Runnable R); // Thread ⇒

R.run()

public Thread(Runnable R, String name); public void start(); // begin thread execution

Trang 59

More Thread Class Methods

public class Thread {

public String getName();

public void interrupt();

public boolean isAlive();

public void join();

public void setDaemon(boolean on);

public void setName(String name);

public void setPriority(int level);

public static Thread currentThread();

public static void sleep(long milliseconds);

Trang 60

Creating Threads in Java

 Runnable interface

 Create object implementing Runnable interface

 Pass it to Thread object via Thread constructor

 Example

public class MyT implements Runnable {

public void run() {

… // work for thread

}

}

Trang 61

Alternative (Not Recommended)

 Directly extend Thread class

public class MyT extends Thread {

public void run() {

… // work for thread

}

}

Trang 62

Why not recommended?

 Not a big problem for getting started

 but a bad habit for industrial strength development

 The methods of the worker class and the Thread class get all tangled up

 Makes it hard to migrate to Thread

Trang 63

Threads – Thread States

 Java thread can be in one of these states

 New – thread allocated & waiting for start()

 Runnable – thread can execute

 Blocked – thread waiting for event (I/O, etc.)

 Terminated – thread finished

 Transitions between states caused by

Trang 64

Threads – Thread States

State diagram

runnable new

Trang 65

Threads – Scheduling

 Scheduler

 Determines which runnable threads to run

 Can be based on thread priority

 Part of OS or Java Virtual Machine (JVM)

 Many computers can run multiple threads simultaneously (or nearly so)

Trang 66

Java Thread Example

public class ThreadExample implements Runnable { public void run() {

for (int i = 0; i < 3; i++)

System.out.println(i);

}

public static void main(String[] args) {

new Thread(new ThreadExample()).start();

new Thread( new ThreadExample()).start();

Trang 67

Java Thread Example –

Output

 Possible outputs

 0,1,2,0,1,2,Done // thread 1, thread 2, main()

 0,1,2,Done,0,1,2 // thread 1, main(), thread 2

 Done,0,1,2,0,1,2 // main(), thread 1, thread 2

 0,0,1,1,2,Done,2 // main() & threads interleaved

thread 1: println 0, println 1, println 2 main (): thread 1, thread 2, println Done

Trang 68

Might not see different

interleavings

 The threads in that example are too short

 Each started thread will probably

complete before the next thread starts

 Let’s make more threads that run

Trang 69

Data Races

public class DataRace implements Runnable {

static volatile int x;

public void run() {

for (int i = 0; i < 10000; i++) {

x++;

x ;

}

}

public static void main(String[] args) throws Exception {

Thread [] threads = new Thread[100];

for (int i = 0; i < threads.length; i++)

threads[i] = new Thread(new DataRace());

for (int i = 0; i < threads.length; i++)

threads[i].start();

Trang 70

Using Synchronization

public class DataRace implements Runnable {

static volatile int x;

static Object lock = new Object();

public void run() {

for (int i = 0; i < 10000; i++)

synchronized(lock) {

x++; x ;

}

}

public static void main(String[] args) throws Exception {

Thread [] threads = new Thread[100];

for (int i = 0; i < threads.length; i++)

threads[i] = new Thread(new DataRace());

for (int i = 0; i < threads.length; i++)

threads[i].start();

Trang 71

Loading, Displaying and Scaling Images

Loading and Playing Audio Clips

Animating a Series of Images

Customizing Applets via the HTML param Tag

Chapter 12: Multimedia

Trang 72

Loading, Displaying and Scaling

Images

 Java Multimedia

 Graphics, images, animations, sounds, and video

 Begin with images

Class Image (java.awt)

 Abstract class, cannot create an object directly

Must request that an Image be loaded and returned to you

Class Applet (superclass of JApplet) has this method

getImage( imageLocation, filename );

Trang 73

Loading, Displaying and Scaling

Images (II)

Displaying Images with drawImage

 Many overloaded versions

g.drawImage( myImage, x, y, ImageObserver );

myImage - Image object

x,y - coordinates to display image

ImageObserver - object on which image is displayed

Use "this" to indicate the applet

Can be any object that implements ImageObserver interface

g.drawImage( myImage, x, y, width, height,

ImageObserver );

Trang 74

Loading, Displaying and Scaling

Images (III)

Class ImageIcon

 Not an abstract class (can create objects)

 Example constructor

private ImageIcon myIcon;

myIcon = new ImageIcon( "myIcon.gif" );

Displaying Icons with method paintIcon

myIcon.paintIcon( Component, Graphics, x, y )

Trang 75

Loading, Displaying and Scaling

Images (IV)

 Usage

 Create objects directly

No need for ImageObserver reference

However, cannot scale ImageIcons

 Scaling

Trang 76

08/13/14 Võ Phương Bình - ITFAC - DLU 76

Image Example

1 import 1.1 Declare objects

2 init() 2.1 Initialize objects

1 // Fig 30.1: LoadImageAndScale.java

2 // Load an image and display it in its original size

3 // and scale it to twice its original width and height.

4 // Load and display the same image as an ImageIcon.

5 import java.applet.Applet;

6 import java.awt.*;

7 import javax.swing.*;

8

9 public class LoadImageAndScale extends JApplet {

10 private Image logo1;

11 private ImageIcon logo2;

12

13 // load the image when the applet is loaded

14 public void init()

15 {

16 logo1 = getImage( getDocumentBase(), "logo.gif" );

17 logo2 = new ImageIcon( "logo.gif" );

18 }

19

20 // display the image

21 public void paint( Graphics g )

22 {

23 // draw the original image

24 g.drawImage( logo1, 0, 0, this );

25

26 // draw the image scaled to fit the width of the applet

27 // and the height of the applet minus 120 pixels

Trang 77

32 logo2.paintIcon( this , g, 180, 0 );

33 }

34 }

Trang 78

Loading and Playing Audio Clips

 Audio clips

 Require speakers and a sound board

 Sound engine - plays audio clips

Supports au, wav, aif, mid

 Java Media Framework supports additional formats

 Playing audio clips

play method in Applet

 Plays clip once, marked for garbage collection when finished

Trang 79

Loading and Playing Audio Clips

(II)

 Playing audio clips

Method play from AudioClip interface

More flexible than Applet method play

 Audio stored in program, can be reused

getAudioClip

Returns reference to an AudioClip

Same format as Applet method play

getAudioClip( location, filename )

getAudioClip( soundURL )

Once AudioClip loaded, use methods

Trang 80

08/13/14 Võ Phương Bình - ITFAC - DLU 80

1 import 1.1 Declare objects

8 public class LoadAudioAndPlay extends JApplet {

9 private AudioClip sound1, sound2, currentSound;

10 private JButton playSound, loopSound, stopSound;

11 private JComboBox chooseSound;

12

13 // load the image when the applet begins executing

14 public void init()

15 {

16 Container c = getContentPane();

17 c.setLayout( new FlowLayout() );

18

19 String choices[] = { "Welcome", "Hi" };

20 chooseSound = new JComboBox( choices );

Trang 81

08/13/14 Võ Phương Bình - ITFAC - DLU 81

35 ButtonHandler handler = new ButtonHandler();

36 playSound = new JButton( "Play" );

53 // stop the sound when the user switches Web pages

54 // (i.e., be polite to the user)

55 public void stop()

56 {

57 currentSound.stop();

58 }

59

60 private class ButtonHandler implements ActionListener {

61 public void actionPerformed( ActionEvent e )

63 if ( e.getSource() == playSound )

64 currentSound.play();

Ngày đăng: 11/08/2014, 22:23

TỪ KHÓA LIÊN QUAN