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
+157-5Lines changed: 157 additions & 5 deletions
Original file line number
Diff line number
Diff line change
@@ -163,17 +163,18 @@ public class ElseIf {
163
163
164
164
<p>
165
165
Java also supports a <c>switch</c> statement that acts something like the <c>elif</c> statement of Python under certain conditions. To write the grade program using a <c>switch</c> statement we would use the following:
166
-
</p>
166
+
</p>
167
167
168
168
<note>
169
169
<p>
170
-
Depending on your knowledge and experience with Python you may already be familiar and questioning why we are not using the <c>match</c> statement in our Python examples. The answer is that this book currently runs its active code examples on Python 3.7, which does not support the <c>match</c> statement. The <c>match</c> statement was introduced in Python 3.10. Below is an example of the <c>match</c> statement similar to our grade method.
170
+
Depending on your knowledge and experience with Python you may already be familiar and questioning why we are not using the <c>match</c> statement in our Python examples. The answer is that this book currently runs its active code examples using Python 3.7, which does not support the <c>match</c> statement which was introduced in Python 3.10. Below is an example of the <c>match</c> statement similar to our grade method.
171
171
</p>
172
172
<programlanguage="python">
173
173
<title>Match Case Example</title>
174
174
<code>
175
-
grade = 100 // 10
176
-
def grading(grade):
175
+
grade = 85
176
+
tempgrade = grade // 10
177
+
def grading(tempgrade):
177
178
match grade:
178
179
case 10 | 9:
179
180
return 'A'
@@ -185,7 +186,7 @@ Java also supports a <c>switch</c> statement that acts something like the <c>eli
185
186
return 'D'
186
187
case _:
187
188
return 'F'
188
-
print(grading(grade))
189
+
print(grading(tempgrade))
189
190
</code>
190
191
</program>
191
192
</note>
@@ -234,6 +235,157 @@ The <c>switch</c> statement is not used very often, and we recommend you do not
234
235
</p>
235
236
</section>
236
237
238
+
<sectionxml:id="exception-handling">
239
+
<title>Exception Handling</title>
240
+
241
+
<p>
242
+
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:
System.out.print("Please enter a whole number: ");
266
+
int number = user_input.nextInt();
267
+
int squared = number * number;
268
+
269
+
System.out.println("Your number squared is " + squared);
270
+
}
271
+
}
272
+
</code>
273
+
</program>
274
+
275
+
<p>
276
+
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:
number = int(input("Please enter a whole number: "))
284
+
squared = number ** 2
285
+
print("Your number squared is " + str(squared))
286
+
break
287
+
except ValueError:
288
+
print("That was not a valid number. Please try again: ")
289
+
</code>
290
+
</program>
291
+
292
+
<p>
293
+
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.
System.out.print("Please enter a whole number: ");
308
+
int number = scanner.nextInt();
309
+
int squared = number * number;
310
+
System.out.println("Your number squared is " + squared);
311
+
break;
312
+
} catch (InputMismatchException e) {
313
+
System.out.println("That was not a valid number. Please try again: ");
314
+
scanner.nextLine(); // Clear the invalid input from the scanner
315
+
}
316
+
}
317
+
}
318
+
}
319
+
</code>
320
+
</program>
321
+
322
+
<p>
323
+
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.
324
+
</p>
325
+
326
+
<p>
327
+
<idx>checked exception</idx>
328
+
<idx>unchecked exception</idx>
329
+
Exceptions in Java fall under two categories: checked and unchecked. <term>Checked exceptions</term> must be explicitly imported and declared along with <c>try-catch</c> blocks for a program to compile. <term>Unchecked exceptions</term> do not need to be imported unless <c>try-catch</c> blocks are implemented for them (except for <c>java.lang</c> exceptions). <c>InputMismatchException</c> is an unchecked exception that is not part of the <c>java.lang</c> library, so it is only included if <c>try-catch</c> blocks declare it. Here are some common exceptions used with <c>try-catch</c> blocks:
330
+
</p>
331
+
332
+
<table>
333
+
<title>Exceptions</title>
334
+
<tabular>
335
+
<row>
336
+
<cell><term>Exception</term></cell>
337
+
<cell><term>Package</term></cell>
338
+
<cell><term>Description</term></cell>
339
+
</row>
340
+
<row>
341
+
<cell><c>IOException</c></cell>
342
+
<cell><c>java.io</c></cell>
343
+
<cell>Thrown when an I/O operation fails (e.g., reading or writing a file).</cell>
344
+
</row>
345
+
<row>
346
+
<cell><c>FileNotFoundException</c></cell>
347
+
<cell><c>java.io</c></cell>
348
+
<cell>Thrown when an attempt to open a file denoted by a pathname has failed.</cell>
349
+
</row>
350
+
<row>
351
+
<cell><c>ParseException</c></cell>
352
+
<cell><c>java.text</c></cell>
353
+
<cell>Thrown when parsing a string into a date, number, etc. fails (e.g., wrong format).</cell>
354
+
</row>
355
+
<row>
356
+
<cell><c>NoSuchMethodException</c></cell>
357
+
<cell><c>java.lang</c></cell>
358
+
<cell>Thrown when a particular method cannot be found via reflection.</cell>
359
+
</row>
360
+
<row>
361
+
<cell><c>InputMismatchException</c></cell>
362
+
<cell><c>java.util</c></cell>
363
+
<cell>Thrown when <c>Scanner</c> input doesn’t match the expected data type.</cell>
364
+
</row>
365
+
<row>
366
+
<cell><c>SQLException</c></cell>
367
+
<cell><c>java.sql</c></cell>
368
+
<cell>Thrown when a database access error occurs (e.g., invalid SQL query, bad connection).</cell>
369
+
</row>
370
+
<row>
371
+
<cell><c>InstantiationException</c></cell>
372
+
<cell><c>java.lang</c></cell>
373
+
<cell>Thrown when trying to create an instance of an abstract class or interface.</cell>
374
+
</row>
375
+
<row>
376
+
<cell><c>IllegalAccessException</c></cell>
377
+
<cell><c>java.lang</c></cell>
378
+
<cell>Thrown when a reflection operation tries to access a field or method it doesn't have permission for.</cell>
379
+
</row>
380
+
</tabular>
381
+
</table>
382
+
383
+
<p>
384
+
Note that as with other structures in Java, <c>try-catch</c> blocks blocks must be encased with braces <c>{}</c>. The most important part of this code is, after <c>catch</c>, there is a set of parenthesis with an exception type and a variable name <c>catch (InputMismatchException e)</c>. This is where we declare a <c>InputMismatchException</c> exception and name it with the variable name <c>e</c>. It is common practice, though not a requirement, to name exception variables <c>e</c> in this manner.
Copy file name to clipboardExpand all lines: source/ch8_filehandling.ptx
+4-10Lines changed: 4 additions & 10 deletions
Original file line number
Diff line number
Diff line change
@@ -4,17 +4,10 @@
4
4
<chapterxml:id="filemmanipulation">
5
5
<title>File Handling</title>
6
6
7
-
<introduction>
8
-
<p>
9
-
File handling is an integral part of programming. Most programming languages have the ability to read from, write to, create, delete, move, and copy files.
10
-
</p>
11
-
</introduction>
12
-
13
-
14
7
<sectionxml:id="file-class-import">
15
8
<title>Class Imports</title>
16
9
<p>
17
-
In Python, most built-in libraries are available without needing to explicitly import additional packages, but some libraries like <c>math</c> do need to be imported. Consider the following.
10
+
File handling is an integral part of programming. Most programming languages have the ability to read from, write to, create, delete, move, and copy files. In Python, most built-in libraries are available without needing to explicitly import additional packages, but some libraries like <c>math</c> do need to be imported. Consider the following.
Java includes a class called <c>File</c> in the <c>io</c> library. The class can be imported with the following line. Be sure to capitalize <c>File</c>.
38
+
Much like the Math class, in order for your program to work with files you need to import classes from libraries. Java includes a class called <c>File</c> in the <c>io</c> library. This class allows you to create File objects, and use its public methods. the following code imports the <c>File</c> class and creates a <c>File</c> object called myFile. for now focus on how the class is imported and used in the program; We will cover the <c>IOException</c> class and <c>createNewFile</c> method later.
0 commit comments