Top Posters
Since Sunday
t
7
m
6
k
6
F
5
j
5
t
5
j
5
G
5
f
5
a
5
d
5
c
5
A free membership is required to access uploaded content. Login or Register.

Ch13 Exception Handling.docx

Uploaded: 6 years ago
Contributor: oseven
Category: Programming
Type: Other
Rating: N/A
Helpful
Unhelpful
Filename:   Ch13 Exception Handling.docx (30.87 kB)
Page Count: 2
Credit Cost: 1
Views: 99
Last Download: N/A
Transcript
Computer Science Notes Chapter 13: Exception Handling These notes are meant to accompany Introduction to Java Programming: Brief Version, eighth edition by Y. Daniel Lang. Book’s Statement of Skills: To distinguish Consider the code below. It illustrates one solution to the problem of what to do if you prompt for an integer, but the user enters a sequence of characters that can not be parsed as an integer. The solution uses what is known as a try-catch block, and is an example of exception handling. In this example, the block of code in the try portion tries to parse integerString into an integer. However, if integerString does not contain a String that can be parsed into an integer, then the parseInt() method throws what is known as an exception; specifically, the NumberFormatException exception. An exception is like an error message. So, if this happens, the catch portion senses that error and does something else in response. In this case, it sends a message that an integer was not entered. import javax.swing.JOptionPane; /** The Homework1007 class implements an application that * illustrates small programming ideas for HW10, Problem #7. */ public class Homework1007 { /**HW10 Question 7 * @param args is not used */ public static void main(String[] args) { int i; while (true) { //prompt the user to enter an integer String integerString = JOptionPane.showInputDialog("Enter an integer (0 to quit):"); //Convert the String into an int try { i = Integer.parseInt(integerString); if (i == 0) { xMethod(2.5, 3.7); return; } JOptionPane.showMessageDialog(null, "i = " + i); } catch (NumberFormatException ex) { JOptionPane.showMessageDialog(null, "That was not an integer"); } }//end while loop }//end main(String[]) public static void xMethod(double x, double y) { System.out.print(x + y); return; }//end method xMethod(double, double) }//end class Homework1007

Related Downloads
Explore
Post your homework questions and get free online help from our incredible volunteers
  999 People Browsing