The course is part of this learning path
In this course, we'll learn about Exception Handling in Java.
- What is an Exception?
- Difference between Error and Exception
- Types of Exceptions
- Try-Catch Block
- Finally Block
- Throw and Throws Keywords
- Exception Methods
- Anyone looking to get Oracle Java Certification
- Those who want to learn the Java Programming language from scratch
- Java developers who want to increase their knowledge
- Beginners with no previous coding experience in Java programming
- Those who want to learn tips and tricks in Oracle Certified Associate – Java SE 8 Programmer certification exams
- No prior knowledge is required about the Java programming language
- Basic computer knowledge
Hi there. In this video, we'll make a sample project to better understand the exception subject. In this project, we're going to develop a menu-driven application to manage a simple bank account. This application will help us to deposit and withdraw money, and show the current balance. Also in this project, we will create our own exception and use it in the program. If you're ready, let's start. First, I'll create a new Java project. I click the 'File' menu and select the 'New Java Project' option. I'll specify the project name as BankAccountBalance. The Java version will be JavaSE-1.8. Don't change the other options, and click the 'Finish' button. In this project, right click on the 'src' folder and select 'New', 'Class'. Specify the package name as BankAccount and class name as InSufficientFundException. And, I click the 'Finish' button to create this class. The InSufficientFundException is a type of user-defined exception. We can create our own exceptions by extending the exception class in Java. Our InSufficientFundException class extends superclass exception.
In this class, we declare a private variable message with string type. Also, we create a constructor for displaying the error message. Let's declare a public constructor named InSufficientFundException, and it takes a parameter- message. In the constructor method, we assign the parameter variable message to the variable message of this class. Let's create the getter method of variable message. To create the getter method, I right-click on the empty area and select 'Source' and 'Generate Getters and Setters'. We choose the get method of the variable and then click on the 'Generate' button. The getMessage() method is generated automatically. We completed our exception class. I'll save the code. Let's create a new class. Right click on the BankAccount package and select 'New', 'Class'. Specify the class name as BankAccount and I click the 'Finish' button. Firstly, I'll declare a variable balance with double type, and I'll declare a constructor named BankAccount() without parameters. In this constructor, I'll initialize the variable balance with the 0.0 value.
Now, I will create a public void method deposit() with one double parameter named amount. In the deposit() method, we assign balance plus amount to the variable balance. That means, if we deposit the money to the account, we increase the balance by adding the amount. Now, I'll create another method. This method will be the withdraw money method. So I write, public void withDraw(); and this method also will take one parameter. In parentheses, I write double amount. In the withDraw() method, I'll create an if statement. If the amount is greater than the balance, then I will throw InSufficientFundException using the throw keyword. So I write, throw new InSufficientFundException(); and as the constructor parameter, I'll show a message. The message can be, "Insufficient Balance. Withdraw process couldn't be completed". As you can see, in the throw part, we got a compilation error. If you place the mouse cursor on the InSufficientFundException class, Eclipse shows a quick fix dialog.
We have two ways to handle InsufficientFundException: we can add a throws declaration or we can surround it with a try-catch block. Eclipse automatically inserts the throws declaration in the method signature. The if block is ready. If the amount is less than the balance, then we assign balance minus amount to the variable balance. This means, if we withdraw the money from the account, we decrease the balance by subtracting the amount. Let's create the getter method of the variable balance by using the shortcut that you did in the Exception class. We'll use the getBalance() method for getting the current balance. I'll save the code. Now, let's create the main test class named Test in the same package, and I'll check the checkbox and click the 'Finish' button. In the main() method, we'll develop a menu-driven application for choosing a process from the bank account menu. First, I'll create a BankAccount object named account by using the new keyword; BankAccount account = new BankAccount(). Then, we need to take inputs from the user by using the Scanner class; Scanner inputScanner = new Scanner(System.in).
Now, I'll declare a variable int choice with no initial value. Now, I'll create a do-while loop. In the do block, first I'll print the title of the program. System.out.println(""). Its name is "-----BANK ACCOUNT MENU-----" with uppercase letters. Now, I'll copy the print method and paste it below five times. Now, let's make some changes. The first option on the menu is Deposit. The second option is Withdraw. The third option is Show Current Balance. And, the last option will be to exit from the menu. So I write, "Press another key to exit". In the last print method, we give the "Select an option: " message to the user. Now, I'll assign the nextInt() method of the Scanner class to the variable choice. Now, generally in menu operations we use switch case statement. Conditional switch expression is variable choice. Now, let's write the condition with the while keyword. If the user selects an option from the menu, the loop should continue. But if the user presses the different keys on the keyboard, the loop should terminate.
So, this loop is executed until the choice is greater than or equal to one, and operator, the choice is less than or equal to three. Now, let's create the cases in the switch block. In the first case of the switch, I'll ask deposit amount from the user by using the print method; System.out.println("Deposit Amount"). Then, I'll call the deposit method from BankAccount class by using the object account, and we pass the nextInt() method of the Scanner class as the parameter, account.deposit(inputScanner.nextInt()), and I'll add the break keyword. In the second case of the switch, before withdrawing money, we'll show the current balance to the user by using the print method, System.out.println("Current Balance: " + account.getBalance()). And then similarly, I'll ask the user for the amount of money to be withdrawn, System.out.println( "Withdraw Amount: "); then, we'll call the withDraw() method from BankAccount class by using the object account. So, in the next line I write, account.withDraw() and I'll pass the nextInt() method of the Scanner class as the parameter.
Inside the parentheses I write, inputScanner.nextInt(). But as you can see, we got a compilation error. If you place the mouse cursor on the error, Eclipse shows a quick fix dialog. I'll choose the second option to handle it, with a try-catch block. Also, I'll change the throwable method with toString() to show exception type in message, System.out.println(e.toString()). And lastly, I'll add the break keyword again just after the try-catch block. In the third case of the switch, we will show the current balance to the user by calling the getBalance() method from BankAccount class. So I write, System.out.println("Current Balance: " + account.getBalance()); and I'll add the break keyword again. Lastly, outside the do-while loop, I'll show a bye message to the user. System.out.println("Bye..."); So, if the user presses any key except 1, 2, and 3, the menu will be exited and this message is displayed. Everything is ready. Let's run the code. You see bank account menu on the console screen. I will enter 1 for menu choice.
It asks "Deposit amount: ". I will enter 500 and turn back to the menu. Let's enter 2. We see the Current Balance as 500 and it asks "Withdraw Amount: ". I will enter 400 and turn back to the menu again. Let's enter 3. We see the Current Balance is 100. Withdraw process is successful because we have enough money in the account. Let's go back to the menu again. Let's enter 2 again. We see the current balance is 100 again. Let's enter 200 for the withdrawal amount. We wait for an exception message because while the balance is 100, we want to withdraw 200. We are waiting for the exception message to occur because there is not enough balance yet. Yes. As you can see, the InSufficientFundException is thrown and the "Insufficient Balance. Withdraw process couldn't be completed" message is displayed. Now, I will press another key on the keyboard to exit. As you can see, the "Bye..." message has appeared on the console because the loop is terminated. Yes, we completed our project successfully. Thus, apart from the predefined exceptions, you can create exceptions according to the program you have developed yourself. I advise you to add new control methods in BankAccount class and test these controls by using the bank account menu. Yes. Let's end our lesson here. See you in the next lesson.
OAK Academy is made up of tech experts who have been in the sector for years and years and are deeply rooted in the tech world. They specialize in critical areas like cybersecurity, coding, IT, game development, app monetization, and mobile development.