Java Threads + Exception Handling – Full
Solutions (All 9)
1) Thread using Thread Class (Sum 1–10)
class SumThread extends Thread {
public void run() {
int sum = 0;
for (int i = 1; i <= 10; i++) sum += i;
[Link]("Sum from 1 to 10 = " + sum);
}
}
class Main {
public static void main(String[] args) {
new SumThread().start();
}
}
Output: Sum from 1 to 10 = 55
Explanation: Thread created by extending Thread class.
2) Thread using Runnable (Even Sum)
class EvenSumRunnable implements Runnable {
public void run() {
int sum = 0;
for (int i = 1; i <= 20; i++) {
if (i % 2 == 0) sum += i;
}
[Link]("Even sum = " + sum);
}
}
class Main {
public static void main(String[] args) {
new Thread(new EvenSumRunnable()).start();
}
}
Output: Even sum = 110
1
3) Two Threads (Total + Odd Sum)
class TotalThread extends Thread {
public void run() {
int sum = 0;
for (int i = 1; i <= 50; i++) sum += i;
[Link]("Total Sum = " + sum);
}
}
class OddRunnable implements Runnable {
public void run() {
int sum = 0;
for (int i = 1; i <= 50; i++) {
if (i % 2 != 0) sum += i;
}
[Link]("Odd Sum = " + sum);
}
}
class Main {
public static void main(String[] args) {
new TotalThread().start();
new Thread(new OddRunnable()).start();
}
}
Output (order may vary): Total Sum = 1275 Odd Sum = 625
4) throw Example (Age Validation)
class ThrowExample {
public static void main(String[] args) {
int age = 16;
try {
if (age < 18)
throw new ArithmeticException("Not eligible for voting");
} catch (ArithmeticException e) {
[Link]([Link]());
}
}
}
Output: Not eligible for voting
2
5) Throwable Example
class ThrowableExample {
public static void main(String[] args) {
try {
int x = 10 / 0;
} catch (Throwable t) {
[Link]([Link]());
[Link]([Link]());
}
}
}
Output: [Link]: / by zero / by zero
6) NullPointerException (String)
class NPE1 {
public static void main(String[] args) {
String s = null;
try {
[Link]([Link]());
} catch (NullPointerException e) {
[Link]("String is null");
}
}
}
Output: String is null
7) NullPointerException (Object)
class Student {
void show() { [Link]("Hello"); }
}
class NPE2 {
public static void main(String[] args) {
Student s = null;
try {
[Link]();
} catch (NullPointerException e) {
[Link]("Object is null");
}
3
}
}
Output: Object is null
8) IOException (Read File)
import [Link];
import [Link];
class ReadFile {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("[Link]");
[Link]("File opened");
[Link]();
} catch (IOException e) {
[Link]("File error: " + e);
}
}
}
Output (if file missing): File error: [Link]
9) IOException (Write File)
import [Link];
import [Link];
class WriteFile {
public static void main(String[] args) {
try {
FileWriter fw = new FileWriter("[Link]");
[Link]("Hello Java");
[Link]();
[Link]("Write success");
} catch (IOException e) {
[Link]("Write error: " + e);
}
}
}
Output: Write success
4
Final Exam Rule
Thread = concurrent execution Exception = error handling without crash
End of Document