Exceptions are interruptions in the normal flow of program thanks to an error and other exceptional issue. If you don't handle it properly, it can cause your entire program to terminate and output an error.
Examples of when exceptions can occur:
when a divide by zero operation was attempted
a network connection being interrupted
a user entering incorrect data
In this lesson, we'll learn how to safely and gracefully handle an exception so that your program can continue running properly.
We're trying to prevent this from happening.
Try Catch block
Exceptions in Java are handled using the try-catch block. The try block is where the code that could throw an exception is run, whereas the catch block is the code that you want to run if an exception is indeed thrown.
This is the format for catching exceptions:
JAVA
try {
// code to try
} catch(Exception e) {
// code to handle exception
}
We can throw our own exceptions! Now if you're wondering why this is useful, well, you can use exceptions to ensure that things in your program are progressing correctly, like this:
JAVA
publicclassMain {
staticvoidcheckMoney(int money) {
if (money < 200) {
thrownewArithmeticException("You must have at least $200.");
} else {
System.out.println("You have enough money!");
}
}
publicstaticvoidmain(String[] args) {
intmoney=100;
checkMoney(money);
}
}
BASH
Exception in thread "main" java.lang.ArithmeticException: You must have at least $200.
at Main.checkMoney(Main.java:5)
at Main.main(Main.java:14)
Now that the method checkMoney can throw an exception of its own, you can choose to handle it like any other risky piece of code:
JAVA
publicclassMain {
staticvoidcheckMoney(int money) {
if (money < 200) {
thrownewArithmeticException("You must have at least $200.");
} else {
System.out.println("You have enough money!");
}
}
publicstaticvoidmain(String[] args) {
intmoney=100;
try {
checkMoney(money);
} catch(ArithmeticException e) {
System.out.println("You must have at least $200.");
}
}
}
BASH
You must have at least $200.
Not only is that a much cleaner output, but you can fully control it entirely, and even run more code if needed.