Java
Error handling
Add input validation with try/catch.
Throw when no book is available
When borrowBook finds no available book, it should throw an error instead of ending silently. You use throw new IllegalStateException to inform the caller.
void borrowBook() {
for (Book b : books) {
if (b.available) {
b.available = false;
return;
}
}
throw new IllegalStateException("Müsait kitap yok");
}
After the loop completes without return, no book is available. At this point throw fires. The caller catches it with try/catch; if not caught, the program crashes. This is the foundation of error handling.
try/catch in main
Since borrowBook can now throw, you must use try/catch when calling it. The second borrow attempt throws, and the error is caught and printed.
try {
cat.borrowBook();
cat.borrowBook();
} catch (IllegalStateException e) {
System.out.println("Hata: " + e.getMessage());
}
The first borrowBook succeeds, the second throws. catch catches the error and getMessage() retrieves the message. This structure lets you handle the error without crashing the program.
Exercise Throw and catch the error
Add throw new IllegalStateException("Müsait kitap yok") at the end of Catalog.borrowBook (after the loop). In main call cat.borrowBook() twice inside try; catch IllegalStateException and print Hata: with getMessage().
Show example solution
// At the end of Catalog.borrowBook (after the loop):
throw new IllegalStateException("Müsait kitap yok");
// inside main:
try {
cat.borrowBook();
cat.borrowBook();
} catch (IllegalStateException e) {
System.out.println("Hata: " + e.getMessage());
}
Test yourself
-
What happens when borrowBook finds no available book?
- Ends silently
- Throws IllegalStateException
- Deletes all books
- Closes the program
Show answer
Throws IllegalStateException — after the loop, throw new IllegalStateException fires; if the caller does not catch it, it crashes.
-
Match each keyword to its purpose
- throw
- Throws exception
- try
- Risky code
- catch
- Catch error
- IllegalStateException
- Error type
-
Complete the catch block
try {
cat.borrowBook();
} catch (____ e) {
System.out.println("Hata: " + e.getMessage());
}
Show answer
try {
cat.borrowBook();
} catch (IllegalStateException e) {
System.out.println("Hata: " + e.getMessage());
}
Next lesson: Putting it together