Python Lesson 15: Exception Handling

Hello everybody,

Michael here, and today I thought I’d start a new series of Python lessons. In this post, I’ll cover exception handling in Python.

For those who are unfamiliar with exception handling in programming, it’s the process of handling errors that may arise in your code (I covered exception handling in Java in the post Java Lesson 12: Try-Catch & Exception Handling).

Exception handling in Python is quite similar to Java exception handling but instead of the try-catch statement that Java uses, Python uses try-except. Let’s see some Python exception handling in action:

try:
  print(4/0)
except:
  print("Divide by 0 error!")

Divide by 0 error!

In this simple error-handling example, I place the code I want to error-test in the try block and I place the exception I want to display in the except block.

What happens if the code has no errors? How should you handle this? Here’s how:

try:
    print(4/1)
except:
    print("Divide by 0 error!")
finally:
    print("Success!")

4.0
Success!

If the code in your try block doesn’t have any errors, you should include a finally block with code to execute the rest of the code. The finally block will execute regardless of the results of the try and except blocks so even if the try block caught an error and the except block gets executed, the finally block will still be executed.

Now, let’s see what happens when you don’t include a try-except block in your code:

print(4/0)

---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-9-4bf1a7e4a751> in <module>
----> 1 print(4/0)

ZeroDivisionError: division by zero

If you don’t have a try-except block in your code and the program has an error, the program simply crashes and throws an error. With a try-except block (or a try- except-finally block) in your code, you can catch errors that your program might raise and keep the program running regardless of how many errors it catches.

Now, what if there were several possible errors you wanted your code to catch? In Python, you can have as many except blocks as you want, but you’d need to put each possible error in it own except block. Here’s how to utilize several except statements in your code:

try:
    print(3.5/0)
except ZeroDivisionError:
    print("Divide by 0 error!")
except:
    print("No floats allowed")

Divide by 0 error!

In this example, I have a try block along with two except blocks. The first except block catches any divide by 0 errors (referred to in Python as ZeroDivisionErrors) that are found in the try block. If there are no divide by 0 errors, the second except block will run IF there are float values in either the dividend or the divisor (I didn’t configure any input validation in my code but you get the point).

Last but not least, is it possible for you to raise an exception based on a specific condition (like if something happens, raise an exception) ? Yes, and here’s an example of how to do so:

password = str(input("Please create a password: "))

if len(password) < 8:
    raise Exception("Please use 8 characters or more for your password!")

Please create a password: hola
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
<ipython-input-14-3ae89fecd594> in <module>
      2 
      3 if len(password) < 8:
----> 4     raise Exception("Please use 8 characters or more for your password!")

Exception: Please use 8 characters or more for your password!

In this example, the user is asked to create a password and if the password is less than 8 characters, an exception is thrown. Since the password I used for this example-hola-only has 4 characters, the exception was thrown with the custom message “Please use 8 characters or more for your password!”.

  • If you want to raise an exception based off of a specific condition, use an if statement with the raise keyword, not a try-except block.
  • You don’t necessarily need a corresponding else statement if you’re raising an exception from a condition, but you should use an else statement if you want a block of code to continue running if no error is thrown.

Python also has plenty of built-in exception types that you can throw based off a certain condition. Here’s an example of one of Python’s many built-in Exception types at work:


username = "employee1"
password = "companywifi"
​
usernameInput = str(input("Please input your username: "))
passwordInput = str(input("Please input your password: "))
​
if (usernameInput != username) & (passwordInput != password):
    raise PermissionError("Incorrect username and/or password!")
else:
    print("Welcome")

Please input your username: GoBrowns2020
Please input your password: ILUVWORK
---------------------------------------------------------------------------
PermissionError                           Traceback (most recent call last)
<ipython-input-18-fd8de8965591> in <module>
      6 
      7 if (usernameInput != username) & (passwordInput != password):
----> 8     raise PermissionError("Incorrect username and/or password!")
      9 else:
     10     print("Welcome")

PermissionError: Incorrect username and/or password!

In this example, I created a simple login authenticator where a employee of a company enters their username and password to access their work laptop. However, if they don’t use the preset username/password combo, then a PermissionError is thrown and the message “Incorrect username and/or password!” is displayed. However, if they use the preset username/password combo, the message “Welcome” is displayed and the user is logged on to the laptop.

  • If you ever needed a simple login authenticator for any program you’re creating, this code will certainly come in handy-customize it however you like!
  • As I mentioned earlier, Python has plenty of built-in exceptions that you can use-here is a link to the documentation that lists all the Python exceptions available https://docs.python.org/3/library/exceptions.html#os-exceptions (this link is for Python 3.9.2, which is the latest version as of March 2021).

Thanks for reading,

Michael

Java Program Demo 3: More Fun With Method Making, Exceptions, Recursion, and Encapsulation

Hello readers,

It’s Michael, and today’s post will be another Java program demo utilizing the concepts covered in the previous four posts (encapsulation, method making, exceptions, and recursion). I thought this would be a good post to show more examples using these four concepts (as well as build upon the other concepts I discussed in the previous 9 Java posts, because after all, the harder concepts in Java build upon the easier concepts).

First let’s do an encapsulation demo. Here’s our method class (the one that has our getter and setter methods):

package demo3;

public class Demo3
{
private double surfaceArea;
private double volume;

public double setSurfaceArea (double radius, double height)
{
surfaceArea = (2*3.14*Math.pow(radius,2)) + (2*3.14*radius*height);
return surfaceArea;
}

public double setVolume (double radius, double height)
{
volume = (3.14*Math.pow(radius, 2)*height);
return volume;
}

}

And here’s our main class (the class where we will run the program):

package demo3;
import java.util.Scanner;

public class DemoClass3
{
public static void main (String [] args)
{
Demo3 cylinder = new Demo3();

Scanner sc = new Scanner(System.in);

System.out.println(“Please give me a radius: “);
double r = sc.nextDouble();

System.out.println(“Please give me a height: “);
double h = sc.nextDouble();

System.out.println(“The cylinder’s surface area is ” + cylinder.setSurfaceArea(r, h));
System.out.println(“The cylinder’s volume is ” + cylinder.setVolume(r, h));
}
}

And here’s some sample output:

run:
Please give me a radius:
9.5
Please give me a height:
11.2
The cylinder’s surface area is 1234.962
The cylinder’s volume is 3173.912
BUILD SUCCESSFUL (total time: 30 seconds)

In the Demo3 class, I have two private double variables-surfaceArea and volume. My two setter methods-setSurfaceArea and setVolume-will set the values of the surfaceArea and volume variables. Oh, and in case you’re wondering where I got the formulas from, they are the formulas for the surface area and volume of a cylinder, respectively.

You will notice that I don’t have any getter methods here. Why? Since I am using formulas to set the values of surfaceArea and volume, using only the setter methods is fine; due to the nature of this program, there is no need to use getter and setter methods (and the code might have been more confusing if I had used both getters and setters).

In my main class, I have a Scanner object and two doubles-r and h-that will serve as the parameters for each setter method (r will be radius and h will be height). R and h will be set based on the user’s input.

  • One thing I wanted to mention that I didn’t mention earlier is that you don’t have to use the words get and set in your getter and setter methods, but it’s a good idea to do so.

Next, here’s a program demonstrating method making and exception handling. First, here’s the method class (the class that contains the method(s) needed for the program):

package demo3;

public class Demo3
{
private double windchill;

public void findWindchill (double airTemp, double windSpeed)
{
try
{
windchill = 35.74 + (0.6215*airTemp) – (35.75*Math.pow(windSpeed, 2)) + (0.4275*airTemp*Math.pow(windSpeed, 16));
System.out.println(“The windchill is: ” + windchill);
}

catch (Exception e)
{
System.out.println(“Sorry please enter a number”);
}
}
}

And here is the main class (the class from where we will run the program):

package demo3;

public class Demo3
{
private double windchill;

public void findWindchill (double airTemp, double windSpeed)
{
try
{
windchill = 35.74 + (0.6215*airTemp) – (35.75*Math.pow(windSpeed, 2)) + (0.4275*airTemp*Math.pow(windSpeed, 16));
System.out.println(“The windchill is: ” + windchill);
}

catch (Exception e)
{
System.out.println(“Sorry please enter a number”);
}
}
}

And here are two sample outputs (one where the exception runs and one where the program runs normally):

run:
Please enter the temperature:
12
Please enter wind speed:
55
The windchill is : 3.596834017946246E28
BUILD SUCCESSFUL (total time: 3 seconds)

run:
Please enter the temperature:
12
Please enter wind speed:
H
Exception in thread “main” java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at demo3.DemoClass3.main(DemoClass3.java:15)
/Users/michaelorozco-fletcher/Library/Caches/NetBeans/8.2/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 5 seconds)

In this program, the method findWindchill will calculate the temperature with windchill using airTemp and windSpeed as parameters-both of which are double.

In the method findWindchill , I have included a try-catch statement. In the try portion, the block of code I will test will calculate and display the windchill. In the catch portion, the message Sorry please enter a number will be displayed should the method catch an error (which would involve either airTemp or windSpeed not being double).

Or so you would think that the Sorry please enter a number message will be displayed (I thought this would happen too). Here’s what you really see:

Exception in thread “main” java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at demo3.DemoClass3.main(DemoClass3.java:15)
/Users/michaelorozco-fletcher/Library/Caches/NetBeans/8.2/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 5 seconds)

So why don’t you see the Sorry please enter a number message? It’s because that, when dealing with double input, Java will automatically throw an InputMismatchException if the input is non-numeric.

In other words, writing a try-catch statement in my findWindchill method wasn’t necessary. I’ll admit that I didn’t realize this at first, and only found out this would happen after browsing through a few StackOverflow forums. Hey, even I learn new things in programming every now and then.

  • StackOverflow is a great resource for any coding questions you might have, but keep in mind that you might have to look through a few forums until you get the answer that you need.

Lastly, here’s a recursion demo, starting with the method class. Notice anything familiar about this program?:

public class Demo3
{
private int month;
private int day;
private String year;

public String findMonth (int month)
{
String m = null;

switch(month)
{
case 1: m = “January”; break;
case 2: m = “February”; break;
case 3: m = “March”; break;
case 4: m = “April”; break;
case 5: m = “May”; break;
case 6: m = “June”; break;
case 7: m = “July”; break;
case 8: m = “August”; break;
case 9: m = “September”; break;
case 10: m = “October”; break;
case 11: m = “November”; break;
case 12: m = “December”; break;

default:
{
System.out.println(“ERROR”);
System.exit(0);

}

}

return m;
}

public String findDay1 (int day)
{
String d = null;

{
switch(day)
{
case 1: d = “1st”; break;
case 2: d = “2nd”; break;
case 3: d = “3rd”; break;
case 4: d = “4th”; break;
case 5: d = “5th”; break;
case 6: d = “6th”; break;
case 7: d = “7th”; break;
case 8: d = “8th”; break;
case 9: d = “9th”; break;
case 10: d = “10th”; break;
case 11: d = “11th”; break;
case 12: d = “12th”; break;
case 13: d = “13th”; break;
case 14: d = “14th”; break;
case 15: d = “15th”; break;
case 16: d = “16th”; break;
case 17: d = “17th”; break;
case 18: d = “18th”; break;
case 19: d = “19th”; break;
case 20: d = “20th”; break;
case 21: d = “21st”; break;
case 22: d = “22nd”; break;
case 23: d = “23rd”; break;
case 24: d = “24th”; break;
case 25: d = “25th”; break;
case 26: d = “26th”; break;
case 27: d = “27th”; break;
case 28: d = “28th”; break;
case 29: d = “29th”; break;
case 30: d = “30th”; break;

default:
{
System.out.println(“ERROR”);
System.exit(0);
}
}

return d;
}
}

public String findDay2 (int day)
{
String d2 = null;

switch(day)
{
case 1: d2 = “1st”; break;
case 2: d2 = “2nd”; break;
case 3: d2 = “3rd”; break;
case 4: d2 = “4th”; break;
case 5: d2 = “5th”; break;
case 6: d2 = “6th”; break;
case 7: d2 = “7th”; break;
case 8: d2 = “8th”; break;
case 9: d2 = “9th”; break;
case 10: d2 = “10th”; break;
case 11: d2 = “11th”; break;
case 12: d2 = “12th”; break;
case 13: d2 = “13th”; break;
case 14: d2 = “14th”; break;
case 15: d2 = “15th”; break;
case 16: d2 = “16th”; break;
case 17: d2 = “17th”; break;
case 18: d2 = “18th”; break;
case 19: d2 = “19th”; break;
case 20: d2 = “20th”; break;
case 21: d2 = “21st”; break;
case 22: d2 = “22nd”; break;
case 23: d2 = “23rd”; break;
case 24: d2 = “24th”; break;
case 25: d2 = “25th”; break;
case 26: d2 = “26th”; break;
case 27: d2 = “27th”; break;
case 28: d2 = “28th”; break;

default:
{
System.out.println(“ERROR”);
System.exit(0);
}
}
return d2;
}

public String findDay3 (int daÿ)
{
{
String d3 = null;

switch(day)
{
case 1: d3 = “1st”; break;
case 2: d3 = “2nd”; break;
case 3: d3 = “3rd”; break;
case 4: d3 = “4th”; break;
case 5: d3 = “5th”; break;
case 6: d3 = “6th”; break;
case 7: d3 = “7th”; break;
case 8: d3 = “8th”; break;
case 9: d3 = “9th”; break;
case 10: d3 = “10th”; break;
case 11: d3 = “11th”; break;
case 12: d3 = “12th”; break;
case 13: d3 = “13th”; break;
case 14: d3 = “14th”; break;
case 15: d3 = “15th”; break;
case 16: d3 = “16th”; break;
case 17: d3 = “17th”; break;
case 18: d3 = “18th”; break;
case 19: d3 = “19th”; break;
case 20: d3 = “20th”; break;
case 21: d3 = “21st”; break;
case 22: d3 = “22nd”; break;
case 23: d3 = “23rd”; break;
case 24: d3 = “24th”; break;
case 25: d3 = “25th”; break;
case 26: d3 = “26th”; break;
case 27: d3 = “27th”; break;
case 28: d3 = “28th”; break;
case 29: d3 = “29th”; break;
case 30: d3 = “30th”; break;
case 31: d3 = “31st”; break;

default:
{
System.out.println(“ERROR”);
System.exit(0);
}

}
return d3;
}
}

public String findYear (String year)
{
String y = null;

switch(year)
{
case “00”: y = “2000”; break;
case “01”: y = “2001”; break;
case “02”: y = “2002”; break;
case “03”: y = “2003”; break;
case “04”: y = “2004”; break;
case “05”: y = “2005”; break;
case “06”: y = “2006”; break;
case “07”: y = “2007”; break;
case “08”: y = “2008”; break;
case “09”: y = “2009”; break;
case “10”: y = “2010”; break;
case “11”: y = “2011”; break;
case “12”: y = “2012”; break;
case “13”: y = “2013”; break;
case “14”: y = “2014”; break;
case “15”: y = “2015”; break;
case “16”: y = “2016”; break;
case “17”: y = “2017”; break;
case “18”: y = “2018”; break;
case “19”: y = “2019”; break;

default:
{
System.out.println(“ERROR”);
System.exit(0);
}
}

return y;
}
}

And here’s the main class:

package demo3;
import java.util.Scanner;

public class DemoClass3
{
public static void main (String [] args)
{
Demo3 date = new Demo3 ();
Scanner sc = new Scanner (System.in);

System.out.println(“Please enter a number: “);
int month = sc.nextInt();

System.out.println(“Please enter a number: “);
int day = sc.nextInt();

System.out.println(“Please enter a two digit String: “);
String year = sc.next();

if (month == 4 || month == 6 || month == 9 || month == 11)
{
System.out.println(“The date is: ” + date.findMonth(month) + ” ” + date.findDay1(day) + ” , ” + date.findYear(year));
}

else if (month == 2)
{
System.out.println(“The date is: ” + date.findMonth(month) + ” ” + date.findDay2(day) + ” , ” + date.findYear(year));
}

else
{
System.out.println(“The date is: ” + date.findMonth(month) + ” ” + date.findDay3(day) + ” , ” + date.findYear(year));
}
}
}

And here are two sample outputs, one where the program runs as normal, and another where the default case is executed:

run:
Please enter a number:
11
Please enter a number:
27
Please enter a two digit String:
19
The date is: November 27th , 2019
BUILD SUCCESSFUL (total time: 13 seconds)

run:
Please enter a number:
11
Please enter a number:
31
Please enter a two digit String:
19
ERROR
BUILD SUCCESSFUL (total time: 6 seconds)

Alright, so the familiar thing about this program is that it is a more complicated version of the recursion example from Java Lesson 13: Recursion (the one where you enter a number and return a month). However, unlike that program, you are trying to put together a whole date using three variables-month, day, and  year.

But that’s not all. See, the month and day variables are int but the year is actually a String. Ok, so year is really a two-digit String that can range from 00 to 19 (representing 2000 to 2019). From that two-digit string, the full year is returned.

The method class has 5 methods: findMonth, findDay1, findDay2, findDay3 and findYear.  If you’ll notice from the code,  the findDay methods do the same basic thing; the only difference is that findDay1 has 30 cases, findDay2 has 28 cases, and findDay3 has 31.

As for why I made three different findDay methods, here’s a poem that explains my reasoning:

Thirty days hath September
April, June and November
All the rest have 31
Except for February which has 28

See, depending on the value for the month that the user enters, I needed three different findDay methods to handle every appropriate scenario, since not all months have the same amount of days.

And yes, I know February has a 29th every four years, but I didn’t feel like overcomplicating this program. If you tried to input a date such as February 29, 2016, you would get an error:

run:
Please enter a number:
2
Please enter a number:
29
Please enter a two digit String:
16
ERROR
BUILD SUCCESSFUL (total time: 21 seconds)

As for the two pieces of sample output shown earlier, the first piece shows the output when month=11, day=27, year="19" (that output is November 27, 2019 , the day this post was published). The second piece shows the output when month=11, day=31, year "19" (this returns an error message, since there is no such date as November 31, 2019).

Thanks for reading and Happy Thanksgiving,

Michael

Java Lesson 12: Try-Catch & Exception Handling

Hello everybody,

It’s Michael, and today’s Java lesson will be on try-catch statements and exception handling in Java.

In Java lingo, exceptions are errors that occur in the program, which can be caused by coding errors made by the programmer, errors caused by incorrect input (in programs that utilize user input), or other unforeseeable things. When errors occur, Java will generate an error message-the technical term for this is throwing an exception.

Now let’s demonstrate errors in action. Consider the following program:

public class TryCatch
{
public static void main (String [] args)
{
int [] numbers = {1, 1, 2, 3, 5, 8, 13, 21, 34};
System.out.println(numbers[11]);
}
}

And here’s the error message we get when we try to run this code:

run:
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 11
at JavaLesson12.TryCatch.main(TryCatch.java:17)
/Users/michaelorozco-fletcher/Library/Caches/NetBeans/8.2/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)

In this example, we get an ArrayIndexOutOfBoundsException when we try to run the code. This is just one of the many types of exceptions you might run into.

We get this particular exception because we are trying to retrieve an array index that doesn’t exist. Since there are only 9 elements in this array, the highest index we can use is 8.

Now, let’s fix this program using a try-catch statement:

public class TryCatch
{
public static void main (String [] args)
{
try
{
int [] numbers = {1, 1, 2, 3, 5, 8, 13, 21, 34};
System.out.println(numbers[11]);
}

catch (Exception e)
{
System.out.println(“Index out of bounds!”);
}
}
}

And here’s the output:

run:
Index out of bounds!
BUILD SUCCESSFUL (total time: 0 seconds)

So what exactly does the try-catch statement do? This statement (or rather statement pair) tries to catch an error (or exception) and, should an error be found, executes the block of code in the catch statement. In this case, an error is found, so the code in the catch statement is executed (the only thing that happens here is that Index out of bounds! is printed).

  • Never have a try statement without a corresponding catch statement!
  • The catch statement will always have Exception e as a parameter (though I’m not sure why).

You can also use the word finally after a try-catch statement. All this does is execute code after a try-catch statement is finished running (regardless of whether or not an error is found). Here’s an example:

public class TryCatch
{
public static void main (String [] args)
{
try
{
int [] numbers = {1, 1, 2, 3, 5, 8, 13, 21, 34};
System.out.println(numbers[11]);
}

catch (Exception e)
{
System.out.println(“Index out of bounds!”);
}

finally
{
System.out.println(“All done here”);
}
}
}

And here’s the output:

run:
Index out of bounds!
All done here
BUILD SUCCESSFUL (total time: 1 second)

There are basically no changes in the way the program runs-an error is found, so Index out of bounds! is printed. The only difference between this program and the one in the previous example is that the message All done here is printed after the try-catch statement is finished running. This happens because All done here is the block of code that corresponds to the finally statement.

  • Finally statements will ALWAYS go after try-catch statements!

The last thing I wanted to discuss in this post is the throw statement. In Java, throw works similar to try-catch statements, except it allows you to create a custom error. Throw is always used with a Java exception type.

Here’s a sample program with throw (it’s not the same one from the previous examples):

import java.util.Scanner;

public class TryCatch
{
public static void main (String [] args)
{
Scanner sc = new Scanner (System.in);
int a, b, quotient;

System.out.println(“Please pick a number: “);
a = sc.nextInt();

System.out.println(“Pick another number: “);
b = sc.nextInt();

quotient = a/b;

if (b == 0)
{
throw new ArithmeticException (“Can’t divide by 0”);
}

else
{
System.out.println(“The quotient is: ” + quotient);
}
}
}

And here’s the output with b as 0:

run:
Please pick a number:
11
Pick another number:
0
Exception in thread “main” java.lang.ArithmeticException: / by zero
at JavaLesson12.TryCatch.main(TryCatch.java:27)
/Users/michaelorozco-fletcher/Library/Caches/NetBeans/8.2/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 6 seconds)

Here’s the output with b not being 0:

run:
Please pick a number:
15
Pick another number:
5
The quotient is: 3
BUILD SUCCESSFUL (total time: 3 seconds)

In this program, I have a Scanner object and three int variables-a, b, and quotient (which equals a/b). After I set up the Scanner object, I ask the user to pick two numbers-the first number will be equal to a and the second number to b. I then divide a by b and store the result in the quotient variable.

An ArithmeticException will be thrown if b equals 0, since you can’t divide anything by 0. In the first example, I set b to 0 and my program threw an ArithmeticException. However in my second example, I set b to 3 and instead got the message The quotient is: 3.

  • Throw statements are often used with custom methods, but those aren’t always necessary (after all, I didn’t use a custom method in this example). For more on custom methods, please read my previous post Java Lesson 11: Method Making.
  • There are at least a good 150 exception types in Java, so there’s no need to memorize them all. Here’s a handy guide to the various exception types in Java. Click on an exception type to learn more about it.

Thanks for reading,

Michael