38
Exepction Handling Exception handling enables you to create applications that can resolve (or handle) exceptions. In many cases, handling an exception allows a program to continue executing as if no problem had been encountered.

Exepction Handling Exception handling enables you to create applications that can resolve (or handle) exceptions. In many cases, handling an exception

Embed Size (px)

Citation preview

Exepction Handling

Exception handling enables you to create applications that can resolve (or handle) exceptions.

In many cases, handling an exception allows a program to continue executing as if no problem had been encountered.

Divide by Zero without Exception Handling import java.util.Scanner; public class DivideByZeroNoExceptionHandling { public static int quotient(int numerator, int denominator) { return numerator / denominator; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Please enter an integer numerator: "); int numerator = scanner.nextInt(); System.out.print("Please enter an integer denominator: "); int denominator = scanner.nextInt(); int result = quotient(numerator, denominator); System.out.printf( "%nResult: %d / %d = %d%n", numerator, denominator, result); } }

Please enter an integer numerator: 100Please enter an integer denominator: 7 Result: 100 / 7 = 14

Please enter an integer numerator: 100 Please enter an integer denominator: 0 Exception in thread "main" java.lang.ArithmeticException: / by zero at DivideByZeroNoExceptionHandling.quotient(DivideByZeroNoExceptionHandling.java:10) at DivideByZeroNoExceptionHandling.main(DivideByZeroNoExceptionHandling.java:22)

Please enter an integer numerator: 100 Please enter an integer denominator: hello Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at DivideByZeroNoExceptionHandling.main( DivideByZeroNoExceptionHandling.java:20)

Stack Trace

The first sample executio shows a successful division. In the second execution, the user enters the value 0 as the denominator. Several lines of information are displayed in response to this invalid input. This information is known as a stack trace, which includes the name of the exception (java.lang.ArithmeticException) in a descriptive message that indicates the problem that occurred and the method-call stack (i.e., the call chain) at the time it occurred. The stack trace includes the path of execution that led to the exception method by method. This helps you debug the program.

Handling ArithmeticExceptions and InputMismatchExceptions

The application uses exception handling to process any ArithmeticExceptions and InputMistmatchExceptions that arise. The application still prompts the user for two integers and passes them to method quotient, which calculates the quotient and returns an int result. This version of the application uses exception handling so that if the user makes a mistake, the program catches and handles (i.e., deals with) the exception—in this case, allowing the user to re-enter the input.

import java.util.InputMismatchException; import java.util.Scanner; public class DivideByZeroWithExceptionHandling { public static int quotient(int numerator, int denominator) throws ArithmeticException { return numerator / denominator; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); boolean continueLoop = true; do { try { System.out.print("Please enter an integer numerator: "); int numerator = scanner.nextInt(); System.out.print("Please enter an integer denominator: "); int denominator = scanner.nextInt(); int result = quotient(numerator, denominator); System.out.printf("%nResult: %d / %d = %d%n", numerator, denominator, result); continueLoop = false; // input successful; end looping }

catch (InputMismatchException inputMismatchException) { System.err.printf("%nException: %s%n", inputMismatchException); scanner.nextLine(); // discard input so user can try again System.out.printf( "You must enter integers. Please try again.%n%n"); } catch (ArithmeticException arithmeticException) { System.err.printf("%nException: %s%n", arithmeticException); System.out.printf( "Zero is an invalid denominator. Please try again.%n%n"); } } while (continueLoop); } } // end class DivideByZeroWithExceptionHandling

Please enter an integer numerator: 100 Please enter an integer denominator: 7 Result: 100 / 7 = 14

Please enter an integer numerator: 100 Please enter an integer denominator: 0Exception: java.lang.ArithmeticException: / by zero Zero is an invalid denominator. Please try again.

Please enter an integer numerator: 100 Please enter an integer denominator: 7 Result: 100 / 7 = 14

Please enter an integer numerator: 100 Please enter an integer denominator: hello Exception: java.util.InputMismatchException You must enter integers. Please try again.

Please enter an integer numerator: 100 Please enter an integer denominator: 7result: 100 / 7 = 14

Enclosing Code in a try Block A try block encloses the code that might throw an exception and the

code that should not execute if an exception occurs if an exception occurs, the remaining code in the try block will be skipped).

A try block consists of the keyword try followed by a block of code enclosed in curly braces.

we use the term “try block” to refer to the block of code that follows the try keyword,

The statements that read the integers from the keyboard each use method nextInt to read an int value.

Method nextInt throws an InputMismatchException if the value read in is not an integer.

The division that can cause an ArithmeticException is not performed in the try block.

The call to method quotient invokes the code that attempts the division the JVM throws an ArithmeticException object when the denominator is zero.

Exceptions may surface through explicitly mentioned code in a try block through deeply nested method calls initiated by code in a try block or

from the Java Virtual Machine as it executes Java bytecodes. At least one catch block or a finally block must immediately

follow the try block. Each catch block specifies in parentheses an exception

parameter that identifies the exception type the handler can process.

When an exception occurs in a try block, the type in the catch block matches the thrown exception type exactly or is a direct or indirect superclass of it.

The exception parameter’s name enables the catch block to interact with a caught exception object

use the System.err (standard error stream) object to output error messages. By default, System.err’s print methods, like those of System.out,

display data to the command prompt.

Java Exception Hierarchy

Java Exception Hierarchy small portion of the inheritance hierarchy for class Throwable a

subclass of Object Throwable is the superclass of class Exception and Eror

Only Throwable objects can be used with the exception-handling mechanism.

Class Throwable has two direct subclasses: Exception and Error. Class Exception and its subclasses—for instance, RuntimeException

(package java.lang) and IOException (package java.io)—represent exceptional situations that can occur in a Java program and that can be caught by the application.

Class Error and its subclasses represent abnormal situations that happen in the JVM. Most Errors happen infrequently and should not be caught by

applications—it’s usually not possible for applications to recover from Errors.

Swing (Java)

Swing is a GUI widget toolkit for Java. It is part of Oracle's Java Foundation Classes (JFC)It is an API for providing a graphical user interface (GUI) for

Java programsSwing was developed to provide a more sophisticated

set of GUI components than the earlier Abstract Window Toolkit (AWT).

Swing provides a native look and feel that emulates the look and feel of several platforms,

Swing also supports a pluggable look and feel that allows applications to have a look and feel unrelated to the underlying platform.

Swing vs. AWT In Java’s early days, GUIs were built with components from

the Abstract Window Toolkit (AWT) in package java.awt. These look like the native GUI components of the platform

on which a Java program executes. For example:

a Button object displayed in a Java program running on Microsoft Windows looks like those in other Windows applications.

On Apple Mac OS X, the Button looks like those in other Mac applications.

Sometimes, even the manner in which a user can interact with an AWT component differs between platforms. The component’s appearance and the way in which the user

interacts with it are known as its look-and-feel.

Swing (Java)

It has more powerful and flexible components than AWT. In addition to familiar components such as buttons,

check boxes and labels, Swing provides several advanced components such as tabbed panel, scroll panes, trees, tables, and lists.

Unlike AWT components, Swing components are not implemented by platform-specific code. they are written entirely in Java and therefore are

platform-independent. The term "lightweight" is used to describe such an

element.

Lightweight vs. Heavyweight GUI Components

Most Swing components are lightweight components they’re written, manipulated and displayed completely

in Java. AWT components are heavyweight components,

they rely on the local platform’s windowing system to determine their functionality and their look-and-feel.

Several Swing components are heavyweight components.

Superclasses of Swing’s Lightweight GUI Components

Class Component (package java.awt) is a superclass that declares the common features of GUI components in packages java.awt and javax.swing.

Any object that is a Container (package java.awt) can be used to organize Components by attaching the Components to the Container.

Containers can be placed in other Containers to organize a GUI. Class JComponent (package javax.swing) is a subclass of Container.

JComponent is the superclass of all lightweight Swing components JComponent declares their common attributes and behaviors. Because JComponent is a subclass of Container, all lightweight Swing components

are also Containers

Some common features of JComponent

A pluggable look-and-feel for customizing the appearance of components (e.g., for use on particular platforms).

Shortcut keys (called mnemonics) for direct access to GUI components through the keyboard. Y

Brief descriptions of a GUI component’s purpose (called tool tips) that are displayed when the mouse cursor is positioned over the component for a short time.

Support for accessibility, such as braille screen readers for the visually impaired.

Support for user-interface localization—that is, customizing the user interface to display in different languages and use local cultural conventions.

History of Swing

The Internet Foundation Classes (IFC) were a graphics library for Java originally developed by Netscape Communications Corporation and first released on December 16, 1996.

On April 2, 1997, Sun Microsystems and Netscape Communications Corporation announced their intention to incorporate IFC with other technologies to form the Java Foundation Classes.

The "Java Foundation Classes" were later renamed "Swing."

Basic Properties Swing introduced a mechanism that allowed the look and

feel of every component in an application to be altered without making substantial changes to the application code.

The introduction of support for a pluggable look and feel allows Swing components to emulate the appearance of native components while still retaining the benefits of platform independence.

Originally distributed as a separately downloadable library, Swing has been included as part of the Java Standard Edition since release 1.2.

The Swing classes and components are contained in the javax.swing package hierarchy.

ArchitectureSwing is a platform-independent, Model-View-Controller GUI framework for Java, which follows a single-threaded programming* model.This framework provides a layer of abstraction between the code structure and graphic presentation of a Swing-based GUI.

a thread of execution is the smallest sequence of programmed instructions that can be managed independently by a scheduler, which is typically a part of the operating system.

Model-View-Controller GUI A controller can send commands to the model

to update the model's state (e.g., editing a document). It can also send commands to its associated view

to change the view's presentation of the model (e.g., by scrolling through a document).

A model notifies its associated views and controllers when there has been a change in its state. This notification allows the views to produce

updated output, and the controllers to change the available set of commands.

A view requests information from the model that it uses to generate an output representation to the user.

IDE Support for GUI Design

Many IDEs provide GUI design tools with which you can specify a component’s size, location and other attributes in a visual manner by using the mouse, the keyboard and drag-and-drop.

The IDEs generate the GUI code for you. This greatly simplifies creating GUIs, but each IDE

generates this code differently.For this reason, the GUI code is written by hand, as

you’ll see in the source-code files To build each GUI is encouraged visually using your

preferred IDE(s).

Sample GUI: The SwingSet3 Demo Application

Simple GUI-Based Input/Output with JOptionPane

import javax.swing.JOptionPane; // Addition program that uses JOptionPane for input and output. public class Addition { public static void main(String[] args) { // obtain user input from JOptionPane input dialogs String firstNumber = JOptionPane.showInputDialog("Enter first integer"); String secondNumber = JOptionPane.showInputDialog("Enter second integer"); // convert String inputs to int values for use in a calculation int number1 = Integer.parseInt(firstNumber); int number2 = Integer.parseInt(secondNumber); int sum = number1 + number2; // display result in a JOptionPane message dialog JOptionPane.showMessageDialog( null, "The sum is " + sum, "Sum of Two Integers", JOptionPane.PLAIN_MESSAGE); } }

Addition program that uses JOptionPane for input and output.

Input Dialogs

After the class JOptionPane is imported, the local String variable firstNumber is declared and it is assigned to the result of the call to JOptionPane static method showInputDialog.

This method displays an input dialog using the method’s String argument ("Enter first integer") as a prompt.

Input DialogsThe user types characters in the text field, then clicks OK or

presses the Enter key to submit the String to the program.Clicking OK also dismisses (hides) the dialog.

Unlike Scanner, which can be used to input values of several types from the user at the keyboard, an input dialog can input only Strings.

This is typical of most GUI components. The user can type any characters in the input dialog’s text

field. The program assumes that the user enters a valid integer. If the user clicks Cancel, showInputDialog returns null. If the user either types a noninteger value or clicks the

Cancel button in the input dialog, an exception will occur and the program will not operate correctly.

Converting Strings to int Values

To perform the calculation, we convert the Strings that the user entered to int values.

Recall that the Integer class’s static method parseInt converts its String argument to an int value and might throw NumberFormatException.

Message Dialogs JOptionPane static method showMessageDialog displays a message dialog

containing the sum. The first argument helps the Java application determine where to position

the dialog box. A dialog is typically displayed from a GUI application with its own window. The first argument refers to that window (known as the parent window) and causes

the dialog to appear centered over the parent If the first argument is null, the dialog box is displayed at the center of your screen.

The second argument is the message to display, for example the result of concatenating the String "The sum is " and the value of sum.

The third argument—"Sum of Two Integers"—is the String that should appear in the title bar at the top of the dialog.

The fourth argument—JOptionPane.PLAIN_MESSAGE—is the type of message dialog to display. A PLAIN_MESSAGE dialog does not display an icon to the left of the message. Class JOptionPane provides several overloaded versions of methods

showInputDialog and showMessageDialog, as well as methods that display other dialog types

javax.swing

Class JOptionPane Java.lang.Object java.awt.Component java.awt.Container javax.swing.JComponent javax.swing.JOptionPane

JOptionPane Message Dialog Constants

All message dialog types except PLAIN_MESSAGE display an icon to the left of the message.

These icons provide a visual indication of the message’s importance to the user.

A QUESTION_MESSAGE icon is the default icon for an input dialog box

Some basic Swing GUI componentsThough it’s possible to perform input and output using the JOptionPane dialogs, most GUI applications require more elaborate user interfaces

Labeling GUI Components

A typical GUI consists of many components. GUI designers often provide text stating the

purpose of each. Such text is known as a label and is created

with a JLabel—a subclass of JComponent. A JLabel displays read-only text, an image, or

both text and an image. Applications rarely change a label’s contents

after creating it.

// JLabels with text and icons. import java.awt.FlowLayout; // specifies how components are arranged import javax.swing.JFrame; // provides basic window features import javax.swing.JLabel; // displays text and imageimport javax.swing.SwingConstants; // common constants used with Swing import javax.swing.Icon; // interface used to manipulate images import javax.swing.ImageIcon; // loads images public class LabelFrame extends Jframe { private final JLabel label1; // JLabel with just text private final JLabel label2; // JLabel constructed with text and icon private final JLabel label3; // JLabel with added text and icon // LabelFrame constructor adds JLabels to JFrame public LabelFrame() { super("Testing JLabel"); setLayout(new FlowLayout()); // set frame layout

// JLabel constructor with a string argument label1 = new JLabel("Label with text"); label1.setToolTipText("This is label1"); add(label1); // add label1 to JFrame // JLabel constructor with string, Icon and alignment arguments Icon bug = new ImageIcon(getClass().getResource( "bug1.png")); label2 = new JLabel("Label with text and icon", bug, SwingConstants.LEFT); label2.setToolTipText("This is label2"); add(label2); // add label2 to Jframe label3 = new JLabel(); // JLabel constructor no arguments label3.setText("Label with icon and text at bottom"); label3.setIcon(bug); // add icon to JLabel label3.setHorizontalTextPosition(SwingConstants.CENTER); label3.setVerticalTextPosition(SwingConstants.BOTTOM); label3.setToolTipText("This is label3"); add(label3); // add label3 to JFrame } }

// LabelTest.java// Testing LabelFrame. import javax.swing.JFrame; public class LabelTest { public static void main(String[] args) { LabelFrame labelFrame = new LabelFrame(); labelFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); labelFrame.setSize(260, 180); labelFrame.setVisible(true); } }

Class LabelFrame extends JFrame to inherit the features of a window. An instance of class LabelFrame is used to display a window containing three JLabels. Three JLabel instance variables are declared and they are instantiated in the LabelFrame constructor The JFrame subclass’s constructor builds the GUI that’s displayed in the window when the application executes. Superclass JFrame’s constructor is invoked with the argument "Testing JLabel". JFrame’s constructor uses this String as the text in the window’s title bar.