What if you could catch every error your code throws without watching it yourself?
Why assertThrows for exceptions in JUnit? - Purpose & Use Cases
Imagine you have a program that should stop and show an error when something goes wrong, like dividing by zero. You try to check this by running the program and watching carefully if it crashes. You do this again and again for every little mistake.
Doing this by hand is slow and easy to miss errors. You might forget to check some cases or not notice the exact error. It's like trying to catch a small bug in a big messy room without a flashlight.
The assertThrows method in JUnit helps you catch these errors automatically. It runs the code and checks if the right error happens. If it does, the test passes. If not, it fails. This saves time and makes sure you never miss a problem.
try { divide(5, 0); fail("Expected exception not thrown"); } catch (ArithmeticException e) { // test passes }
assertThrows(ArithmeticException.class, () -> divide(5, 0));
It lets you quickly and clearly check that your program handles errors correctly, making your code safer and more reliable.
For example, when building a calculator app, you want to be sure it stops and warns users if they try to divide by zero. Using assertThrows tests this automatically every time you change the code.
Manual error checking is slow and easy to miss mistakes.
assertThrows automates checking for expected errors.
This makes tests faster, clearer, and more reliable.