You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: source/ch4_conditionals.ptx
+12-7Lines changed: 12 additions & 7 deletions
Original file line number
Diff line number
Diff line change
@@ -264,19 +264,21 @@ The <c>switch</c> statement is not used very often, and we recommend you do not
264
264
In Python, if you want a program to continue running when an error has occurred, you can use <c>try-except</c> blocks to handle exceptions. If you wanted to write a program that asks the user to enter a whole number and then squares that number, you could use the following code to do so:
@@ -293,12 +295,13 @@ The <c>switch</c> statement is not used very often, and we recommend you do not
293
295
}
294
296
</code>
295
297
</program>
298
+
</listing>
296
299
297
300
<p>
298
301
This code works well, but will end with an exception if the user types anything other than a whole number (such as 12.5 or two). If we wanted to ensure the code will continue to run until the user enters the correct format, we could add <c>try-except</c> (Python) or <c>try-catch</c> (Java) blocks within a <c>while</c> loop that iterates until the user enter the correct code. Adding <c>try-except</c> blocks and a <c>while</c> loop to the Python code will look something like this:
@@ -310,12 +313,13 @@ The <c>switch</c> statement is not used very often, and we recommend you do not
310
313
print("That was not a valid number. Please try again: ")
311
314
</code>
312
315
</program>
316
+
</listing>
313
317
314
318
<p>
315
319
Now that we have Python code that will continuously prompt the user until they enter a whole number, let's look at Java code that accomplishes the same task. Like most other equivalent Java code blocks, this code has a lot of extra bits that are necessary to get working code.
@@ -340,6 +344,7 @@ The <c>switch</c> statement is not used very often, and we recommend you do not
340
344
}
341
345
</code> <stdin> </stdin> <tests> </tests>
342
346
</program>
347
+
</listing>
343
348
344
349
<p>
345
350
Firstly, let's talk about the extra import alongside the <c>Scanner</c> import. In Java, we need to import <c>InputMismatchException</c> because it's not automatically available like basic exceptions. This is different from Python where most exceptions are readily accessible. If you ran the previous Java codeblock without <c>try-catch</c> blocks and entered an erroneous input, you would have got an <c>InputMismatchException</c> exception despite not having imported this class. That being said, removing the explicit import of this library for the <c>try-catch</c> code block above will lead to compilation errors.
0 commit comments