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

Java Lesson 11: Method Making

Welcome back loyal readers,

I’m back after a 34-day hiatus and ready to post more amazing content. This lesson will be on method making in Java, in other words, I will teach you how to create you own methods in Java.

Now, I know I covered method creation in the previous lesson on encapsulation. However, the methods I discussed were simply getter and setter methods; in this lesson, I will discuss how to create any type of method.

Here’s the basic syntax of a method:

    • public/private/protected [return type] method Name (parameter 1, parameter 2 …)

Now, what does this mean? Let me explain:

  • You would usually put public, private, or protected as the first part of the method. These three words serve as access modifiers, which denote which parts of the program can access the method. Here’s a better explanation on each:
    • public-any class in the program can access the method
    • private-only the class where the method is located can access the method
    • protected-the class where the method is located can access the method, but so can any classes in the same package as well as any subclasses of that class can also access that method (don’t worry I’ll demonstrate this later in this post)
  • A return type indicates what type of variable you want to return. The possible return types are the same as the the possible variable types (String, int etc.). However, keep these three things in mind regarding return types:
    • You can only return one item per method.
    • If you don’t want your method to return anything, simply use the word void as the return type.
    • Remember to write a line of code with return [variable name]
  • The method name is honestly pretty self-explanatory.
  • Inside the parentheses, you would put any parameters (variables inside the method) you wish to use-or you could use no parameters if you want. If you want to use multiple parameters, separate each individual parameter with a comma.

Now, let’s demonstrate some method making:

First, here’s our method class-this is the term I will use to describe any class where individual methods are made (not including the main method):

public class ProgramDemo
{
public int add (int a, int b)
{
return a+b;
}

public int subtract (int c, int d)
{
return d-c;
}

public int multiply (int e, int f)
{
return e*f;
}

public double divide (double g, double h)
{
return g/h;
}

public double square (int i)
{
return Math.pow(2, i);
}

public double log10 (double j)
{
return Math.log10(j);
}
}

And here’s our main class-this is the class which has the main method from which we will run this program:

public class Arithmetic
{
public static void main (String [] args)
{
ProgramDemo math = new ProgramDemo ();
System.out.println(math.add(45, 19));
System.out.println(math.subtract(18, 22));
System.out.println(math.multiply(36, 11));
System.out.println(math.divide(13.4, 2.3));
System.out.println(math.square(15));
System.out.println(math.log10(23));
}
}

And here’s the output:

64
4
396
5.82608695652174
32768.0
1.3617278360175928
BUILD SUCCESSFUL (total time: 0 seconds)

The class ProgramDemo is the method class since it has the methods that we will use for the program. The Arithmetic class is the main class since it has the main method, and it is the class from where we will run the program.

Notice how none of the ProgramDemo methods are void; all of the methods in that class have a return type, whether int or double.

In the main class-Arithmetic-I was able to access all of the methods of the ProgramDemo class simply by creating an object of the ProgramDemo class-math. There was no need to use extends here, as the methods are public and thus accessible by the entire program.

After I created the math object, I called all six of its methods, filled in each of the parameters for each method, and used System.out.println to print out the results of each calculation.

  • If you forgot what a logarithm is, here’s a simple explanation:
    • Screen Shot 2019-10-03 at 8.43.37 PM
    • For instance, the base 10 logarithm of 1000 would be 3, as 10 to the power of 3 equals 1000.

But what if our methods were private? Let’s demonstrate by first showing the ProgramDemo class with all of the private methods:

public class ProgramDemo
{
private int add (int a, int b)
{
return a+b;
}

private int subtract (int c, int d)
{
return d-c;
}

private int multiply (int e, int f)
{
return e*f;
}

private double divide (double g, double h)
{
return g/h;
}

private double square (int i)
{
return Math.pow(2, i);
}

private double log10 (double j)
{
return Math.log10(j);
}
}

Now, let’s try to execute our methods with the Arithmetic class  (using the same numerical parameters from the previous example):

public class Arithmetic
{
public static void main (String [] args)
{
ProgramDemo math = new ProgramDemo ();
math.add(45, 19);
math.subtract(18, 22);
math.multiply(36, 11);
math.divide(13.4, 2.3);
math.square(15);
math.log10(23);
}
}

And here’s what happens when we try to run the code:

Exception in thread “main” java.lang.RuntimeException: Uncompilable source code – add(int,int) has private access in ProgramDemo
at Arithmetic.main(Arithmetic.java:6)
/Users/michaelorozco-fletcher/Library/Caches/NetBeans/8.2/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 5 seconds)

Since all of the ProgramDemo methods are private, we can’t access them from the Arithmetic class  (not even with the extends keyword). Notice that the error is something called an exception, which I will discuss more in a future post.

  • I imagine there’s probably a way to access private methods from another class, but I haven’t figured it out yet. Once I do, I’ll discuss it in a future post.

Now let’s make all of the ProgramDemo methods protected:

public class ProgramDemo
{
protected int add (int a, int b)
{
return a+b;
}

protected int subtract (int c, int d)
{
return d-c;
}

protected int multiply (int e, int f)
{
return e*f;
}

protected double divide (double g, double h)
{
return g/h;
}

protected double square (int i)
{
return Math.pow(2, i);
}

protected double log10 (double j)
{
return Math.log10(j);
}
}

And let’s run the code in the Arithmetic class (without changing the parameters):

public class Arithmetic
{
public static void main (String [] args)
{
ProgramDemo math = new ProgramDemo ();
math.add(45, 19);
math.subtract(18, 22);
math.multiply(36, 11);
math.divide(13.4, 2.3);
math.square(15);
math.log10(23);
}
}

Here’s the output:

run:
BUILD SUCCESSFUL (total time: 4 seconds)

OK, so this is a weird case where the methods are still accessible but don’t return anything; this is made even weirder since the methods aren’t of type void , so you would think that we would see returned values.

Interestingly enough, I tried several ways to fix my code so that the output would show (and yet none of them worked). Some of my attempted solutions include:

  • Creating a new package-JavaLesson11-and moving the Arithmetic and ProgramDemo classes to that package (I originally had them in the default package)
    • It’s very easy to create a new package in NetBeans. Simply click on the New File button (located above the interface) and when you are asked what type of file you want, simply click on New Package.
  • Using the phrase extends ProgramDemo in the Arithmetic class-I did this both before and after moving each of these classes into the JavaLesson11 package
    • This also did not work. I thought this would certainly would work, since protected methods can be accessed by subclasses of a certain class (the word extends make a class a subclass of whatever that class extends).
    • Also, after I moved Arithmetic and ProgramDemo to the JavaLesson11 package, I thought using extends would certainly work, since protected methods can be accessed by any class in the same package.

Cases like these are why I try to avoid using protected methods in my Java code. I’ll likely stick to public and private methods from here on out.

Now, the last thing I want to demonstrate is how void methods work. Im going to change two methods in ProgramDemo to void and see if that impacts the output:

package JavaLesson11;

public class ProgramDemo
{
public void add (int a, int b)
{
System.out.println(a+b);
}

protected void subtract (int c, int d)
{
System.out.println(d-c);
}

protected int multiply (int e, int f)
{
return e*f;
}

protected double divide (double g, double h)
{
return g/h;
}

protected double square (int i)
{
return Math.pow(2, i);
}

protected double log10 (double j)
{
return Math.log10(j);
}

}

And here’s the ArithmeticClass along with the corresponding output:

package JavaLesson11;

public class Arithmetic extends ProgramDemo
{
public static void main (String [] args)
{
ProgramDemo math = new ProgramDemo ();
math.add(45, 19);
math.subtract(18, 22);
math.multiply(36, 11);
math.divide(13.4, 2.3);
math.square(15);
math.log10(23);
}
}

run:
64
4
BUILD SUCCESSFUL (total time: 0 seconds)

So I ran the code and only get two numbers-64 and 4-which correspond to the add and subtract methods, respectively. Surprisingly, none of the other results from my other methods were printed.

How could that be? First of all, I only made the add and subtract methods void. As a result, I changed the body of each method by replacing the return statement with a System.out.println line that does the same thing as the non-void add and subtract methods. My guess is that since add and subtract are the only two methods with a System.out.println statement in the body of the method, the results of these methods were the only ones that were displayed in the output.

Thanks for reading. It’s good to be back,

Michael