Practical Application for Java: Using Exception Handling

Instructor: Sebastian Garces

Sebastian has taught programming and computational thinking for University students and just got accepted at PURDUE for Master's degree

Have you noticed that sometimes when you are using an application or browsing the internet, you come across warnings or errors that are difficult to understand? This lesson talks about how errors and warnings can be handled gracefully by using exception handling in java applications.

Lesson Overview & Knowledge Required

In this lesson, you will create a program using Java language. This will help you understand how an Exception is thrown and how it can be caught. We will be working with mathematical operations that can make the program exit or stop abruptly, therefore, we will use exception to manage these errors. Below are the knowledge and skills required to complete this lesson and create the program for exception handling:

  • GUI in Java
  • Running Java applications
  • Strings in Java

Program Code

In order to experiment with exceptions, we will write a programme that divides two integers. Create a Java application with the name ExceptionDemo. This should also be the name of the main class.

import javax.swing.*;
public class ExceptionDemo {
  public static void main(String [] args) {
   /*Declare three integers; two to be input by the user and a third to hold the result after dividing the first two. The numerator and denominator must be assigned starting values because their values will be entered within a try block. Declare an input String to hold the return value of the JOptionPane.showInputDialog() method.*/
   int numerator = 0, denominator = 0, result;
   String inputString;
   /*Add a try block that prompts the user for two values, converts each entered String to and integer, and divides the values, producing result.*/
   try {
    inputString = JOptionPane.showInputDialog(null, "Enter a number to be divided");
    numerator = Integer.parseInt(inputString);
    inputString = JOptionPane.showInputDialog(null, "Enter a number to divide into the first number");
    denominator = Integer.parseInt(inputString);
    result = numerator / denominator;
  }
   /*Add a catch block that catches and ArithmeticException object if division by 0 is attempted. If this block executes, display an error message, and result to 0.*/
   catch(ArithmeticException exception) {
   JOptionPane.showMessageDialog(null, exception.getMessage());
    result = 0;
   }
  JOptionPane.showMessageDialog(null, numerator + " / " + denominator + "\nResult is " + result);
 }
}

This is how you should upload the code to your developer tool. I'm using IntelliJ IDEA locally, which is free. You just need to create the class ExceptionDemo, paste the code into it and run it.

Code Application

We are almost there but this code is missing a few things in order to work properly. Right now, it is only handling the exception thrown by Java. What if you try to divide a number by 0 and the message might not be completely clear. Try adding a personalized message to the user to make the error clearer.

Follow-up Questions

1) Alter the code so you can handle all types of exceptions in the same Catch block with a generic error message.

2) Add a Catch block to handle a exception if a user inputs some value other than a number (string, character, etc), and to handle if the user inputs decimal numbers instead of integers.

To unlock this lesson you must be a Study.com Member.
Create your account

Register to view this lesson

Are you a student or a teacher?

Unlock Your Education

See for yourself why 30 million people use Study.com

Become a Study.com member and start learning now.
Become a Member  Back
What teachers are saying about Study.com
Try it risk-free for 30 days

Earning College Credit

Did you know… We have over 160 college courses that prepare you to earn credit by exam that is accepted by over 1,500 colleges and universities. You can test out of the first two years of college and save thousands off your degree. Anyone can earn credit-by-exam regardless of age or education level.

To learn more, visit our Earning Credit Page

Transferring credit to the school of your choice

Not sure what college you want to attend yet? Study.com has thousands of articles about every imaginable degree, area of study and career path that can help you find the school that's right for you.

Create an account to start this course today
Try it risk-free for 30 days!
Create An Account
Support