Introduction of Java Self-defined Exception

1. Introduction

An unexpected exception during program running may cause severe destruction and disruption; Therefore, high standard exception handling is essential in practical Java programming. Many pre-defined exception types are encoded in JDK already, including JVM(like ArrayIndexOutOfBoundsException) and Programmatic exception(like IllegalStateException) groups; In some scenarios, users want to create their custom exception to ensure proper exception output for debugging and analysis. This article is a simple tutorial to introduce how to make the user-defined exception.

2. Exception Class extends Exception

Here is an example that we create our own exception to provide us feedback on the cause of an unwanted result. Let's assume we have a simple bank account with a deposit and withdraw method as well as a balance field.

import java.math.BigDecimal;

public class BankAccount {
    private BigDecimal balance = BigDecimal.valueOf(0.00);

    public void deposit(BigDecimal money) {
        balance.add(money);
    }

    public void withdraw(BigDecimal money) throws BalanceException {
        if (balance.compareTo(money) < 0) {
            throw new BalanceException("Insufficient Balance");
        }
        balance.subtract(money);
    }

    public BigDecimal getBalance() {
        return balance;
    }
}

Logically, if we want to withdraw more money than our current balance has, there should be a problem in a real-life scenario; However, the balance will just become negative mathematically if no exception is handled. Therefore, we should add our BalanceException to prevent that happen. When our balance is less than money, a user-defined BalanceException would be thrown out.

public class BalanceException extends Exception{
    //It is necessary to extends Exception class here
    BalanceException(String s){
        super(s);//This is the exception message that could be obtained.
    }
}

To create the BalanceException, we need to extend the Exception class as the parent class. Then, a constructor is initiated with an exception message in parentheses.

3. Test Demonstration

Now, we create a test class to show the result of our customed BalanceException. Since we have "throws" an Exception out from "withdraw" method, a try and catch block should surround withdraw method to catch the exception message. As we only deposit 200 dollars in the account, a BalanceException should be thrown out when we withdraw 300 dollars.

import java.math.BigDecimal;

public class Main {
    public static void main(String[] args) {
        BankAccount joe = new BankAccount();
        joe.deposit(BigDecimal.valueOf(200.00));//deposit $200.00 in my account
        joe.getBalance();
        try {
            joe.withdraw(BigDecimal.valueOf(300.00));
        } catch (BalanceException be) {
            be.printStackTrace();
        }
    }
}

The resulting block is here below:

ExceptionHandle.BalanceException: Insufficient Balance
	at ExceptionHandle.BankAccount.withdraw(BankAccount.java:14)
	at ExceptionHandle.Main.main(Main.java:13)

4. Conclusion

Proper exception handling skill is required for all programmers to ensure a smooth and reliable running program. The custom exception is a handy method for us to trace back error sources. Our customed exception class needs "extends" Exception class as parent class while the method throwing the user-defined class should be surrounded with try/catch blocks.

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值