1 Welcome
Hello, my student. Today we will learn exception handling in Java — one of the most important topics in programming. But before we dive into exceptions, let me ask you a question:
What types of errors have you encountered while programming in CPCS203? Think about it for a moment...
Throughout this course, you have seen three types of errors. Let's review each one, because understanding errors is the foundation for understanding exceptions.
2 Syntax Errors (Compile-Time Errors)
A syntax error happens when your code violates the rules of the Java language. Just like every spoken language has grammar rules, Java has syntax rules.
In Arabic: “جدة جميلة” — the adjective comes AFTER the noun. That is Arabic syntax.
In English: “Beautiful Jeddah” — the adjective comes BEFORE the noun.
Every language has its own rules. If you break them, the sentence doesn’t make sense.
In Java, if your syntax is wrong, the program simply won’t compile.
Example A Program with Syntax Errors
SyntaxDemo.javaSyntax errors are the EASIEST to fix. Your IDE tells you exactly where the problem is. The compiler points to the line number and even the exact character. Just follow the arrows!
3 Logical Errors
A logical error is sneaky. The program compiles, runs, and produces output — but the output is WRONG.
In Islam, Zakah is 2.5% of wealth above a certain threshold.
Zakah of 1,000 SAR = 25 SAR
Zakah of 1,000,000 SAR = 25,000 SAR
But imagine your program calculates it as 10% instead of 2.5%...
Example A Program with a Logical Error
ZakahCalculator.javaThe program says 100,000 SAR, but the correct answer is 25,000 SAR. No crashes, no errors — but completely wrong. This is a logical error.
Logical errors are solved by testing. There are techniques like white-box and black-box testing, but that’s not our focus today. The key point is: the compiler cannot help you with logical errors. Only careful testing and code review can catch them.
4 Runtime Errors
Runtime errors are the main character of this chapter. The program compiles, starts running... then suddenly crashes.
Example A Program That Crashes at Runtime
RuntimeDemo.javaConsider the Saudi stock market — Al-Ashum (الأسهم). Billions of riyals traded every day. If the trading system crashes for 3 hours, billions lost. Medical devices, power distribution, banking systems — all must keep running. Runtime errors in these systems are not just bugs; they are catastrophes.
5 Two Core Goals of This Chapter
Now that we understand the three types of errors, here is the big question: What can we do about runtime errors?
Keep these two goals in mind throughout this entire chapter. Every concept — try-catch, finally, throw, throws, custom exceptions — serves these two purposes.
In the next lesson, we will see WHY exception handling is the right approach — Oracle’s three advantages.