Java Exceptions
Java Errors
Even experienced Java developers make mistakes. The key is learning how to spot and fix them!
These pages cover common errors and helpful debugging tips to help you understand what's going
wrong and how to fix it.
Common Compile-Time Errors
Compile-time errors occur when the program cannot compile due
to syntax or type issues.
Here are some examples:
1) Missing Semicolon
int x = 5
[Link](x);
2) Undeclared Variables
[Link](myVar);
3) Mismatched Types
int x = "Hello";
Common Runtime Errors
Runtime errors occur when the program compiles but crashes or
behaves unexpectedly.
Here are some examples:
1) Division by Zero
public class Main {
public static void main(String[] args) {
int x = 10;
int y = 0;
int result = x / y;
[Link](result);
}
}
2)Array Index Out of Bounds
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
[Link](numbers[8]);
}
}
Logical Errors
Logical errors happen when the code runs, but the result is not what you
thought:
public class Main {
public static void main(String[] args) {
int x = 10;
int y = 2;
int sum = x - y;
[Link]("x + y = " + sum);
}
}
Java Exceptions
Different types of errors can occur while running a program -
such as coding mistakes, invalid input, or unexpected situations.
When an error occurs, Java will normally stop and generate an
error message. The technical term for this is: Java will throw an
exception (throw an error).
Exception Handling (try and catch)
Exception handling lets you catch and handle errors during runtime
- so your program doesn't crash.
It uses different keywords:
The try statement allows you to define a block of code to be
tested for errors while it is being executed.
The catch statement allows you to define a block of code to be
executed, if an error occurs in the try block.
The try and catch keywords come in pairs:
Syntax
try {
// Block of code to try
catch(Exception e) {
// Block of code to handle errors
}
Simple program
public class Main {
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
[Link](myNumbers[10]);
} catch (Exception e) {
[Link]("Something went wrong.");
}
}
}
Finally
The finally block always executed whether an exception is thrown or not. The finally is used for
closing resources like db connections, open files and network connections, It is used after a try-catch
block to execute code that must run.
class FinallyExample {
public static void main(String[] args){
int[] numbers = { 1, 2, 3 };
try {
// This will throw ArrayIndexOutOfBoundsException
[Link](numbers[5]);
}
catch (ArrayIndexOutOfBoundsException e){
[Link]("Exception caught: " + e);
}
finally{
[Link]("This block always executes.");
}
[Link]("Program continues...");
}
}
Output of above program
throw and throws Keywords
1. throw: Used to explicitly throw a single exception. We use throw when something goes
wrong (or “shouldn’t happen”) and we want to stop normal flow and hand control to exception
handling.
public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else {
[Link]("Access granted - You are old enough!");
}
}
public static void main(String[] args) {
checkAge(15); // Set age to 15 (which is below 18...)
}
}
Output if age is 15
If we keep age as 20:
The throw statement allows you to create a custom error.
The throw statement is used together with an exception type. There are
many exception types available in Java: ArithmeticException,
FileNotFoundException, ArrayIndexOutOfBoundsException,
SecurityException, etc:
throws:
Declares exceptions that a method might throw, informing the caller
to handle them. It is mainly used with checked exceptions . If a
method calls another method that throws a checked exception, and
it doesn’t catch it, it must declare that exception in its throws clause
import [Link].*;
class Demo {
static void readFile(String fileName) throws IOException {
FileReader file = new FileReader(fileName);
}
public static void main(String[] args){
try {
readFile("[Link]");
} catch (IOException e){
[Link]("File not found: " + [Link]());
}
}
}
Java Multiple Exceptions
Sometimes, different errors (exceptions) can happen in the same try block.
You can handle them with multiple catch blocks.
whenever we needed to handle more than one specific exception but
take some action for all exceptions, we had to have more than one catch
block containing the same code.
One try, Many catch
You can add more than one catch block, and Java will run the first one that matches the thrown exception
type:
public class Main {
catch (ArrayIndexOutOfBoundsException e) {
public static void main(String[] args) {
[Link]("Array index does not
exist.");
try {
}
int[] numbers = {1, 2, 3}; catch (ArithmeticException e) {
[Link]("Cannot divide by zero.");
[Link](numbers[10]); // }
catch (Exception e) {
ArrayIndexOutOfBoundsException
[Link]("Something else went
int result = 10 / 0; // wrong.");
}
ArithmeticException }
}
}
Multiple Catch Block in Java
Starting from Java 7.0, it is possible for a single catch block to catch
multiple exceptions by separating each with | (pipe symbol) in the catch
block.
Catching multiple exceptions in a single catch block reduces code
duplication and increases efficiency. The bytecode generated while
compiling this program will be smaller than the program having
multiple catch blocks as there is no code redundancy.
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0;
int[] numbers = {1, 2, 3};
[Link](numbers[10]);
}
catch (ArithmeticException | ArrayIndexOutOfBoundsException e)
{
[Link]("Math error or array error occurred.");
}
}
}
import [Link];
public class Test
{
public static void main(String args[])
{
Scanner scn = new Scanner([Link]);
try
{
int n = [Link]([Link]());
if (99%n == 0)
[Link](n + " is a factor of 99");
}
catch (NumberFormatException | ArithmeticException ex)
{
[Link]("Exception encountered " + ex);
}
}
}
If input is string
If input is number
Types of Java Exceptions
Java defines several types of exceptions that relate to its various class libraries. Java
also allows users to define their it's exceptions.
1 Built-in Exception
Build-in Exception are predefined exception classes provided by Java to handle
common errors during program execution. There are two type of built-in
exception in java.
● Checked Exception: These exceptions are checked at compile time,
forcing the programmer to handle them explicitly.
● Unchecked Exception: These exceptions are checked at runtime and do
not require explicit handling at compile time.
2. User-Defined Exception
Sometimes, the built-in exceptions in Java are not able to describe a certain
situation. In such cases, users can also create exceptions, which are called
"user-defined Exceptions".
Methods to Print the Exception Information
● toString(): Prints exception information in the format of the Name of the
exception.
● getMessage() : Prints the description of the exception
User-Defined Custom Exception in Java
Java provides us the facility to create our own exceptions by extending the
Java Exception class.
Creating our own Exception is known as a custom exception in Java or a
user-defined exception in Java. In simple words, we can say that a
User-Defined Custom Exception or custom exception is creating your own
exception class and throwing that exception using the "throw" keyword.
// A Class that represents user-defined exception
class MyException extends Exception {
public MyException(String m) {
super(m);
}
}
// A Class that uses the above MyException
public class SetText {
public static void main(String args[]) {
try {
// Throw an object of user-defined exception
throw new MyException("This is a custom exception");
}
catch (MyException ex) {
[Link]("Caught");
[Link]([Link]());
}
}
}
Java Threads
● A Java thread is the smallest unit of execution within a program.
● It is a lightweight subprocess that runs independently but shares
the same memory space as the process, allowing multiple tasks to
execute concurrently.
● Java is a multi-threaded programming language which means we
can develop multi-threaded program using Java.
● A multi-threaded program contains two or more parts that can run
concurrently and each part can handle a different task at the same
time making optimal use of the available resources specially when
your computer has multiple CPUs.
● multitasking is when multiple processes share common processing
resources such as a CPU.
● Multi-threading extends the idea of multitasking into applications
where you can subdivide specific operations within a single
application into individual threads.
● Each of the threads can run in parallel. The OS divides processing
time not only among different applications, but also among each
thread within an application.
Java Multithreading
● Multi-threading enables you to write in a way where multiple
activities can proceed concurrently in the same program.
● To achieve the multithreading (or, write multithreaded code), need
[Link] class.
Life Cycle of a Thread
● New: Thread object is created but not started.
● Runnable: Thread is ready to run and waiting for CPU allocation.
● Running: Thread is executing its run() method.
● Waiting/Blocked: Thread waits for a resource or another thread.
● Terminated: Thread completes execution or is stopped.
Thread Priorities
Every Java thread has a priority that helps the operating system determine the
order in which threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of 1)
and MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be
allocated processor time before lower-priority threads. However, thread priorities
cannot guarantee the order in which threads execute and are very much platform
dependent.
Creating a Thread
We can create threads in java using two ways
By Extending Thread Class
import [Link].*;
import [Link].*;
class MyThread extends Thread{ Create a class that extends
Thread. Override the run()
// initiated run method for Thread method, this is where you put the
public void run(){ code that the thread should
String str = "Thread Started Running..."; execute. Then create an object of
[Link](str); your class and call the start()
} method. This will internally call
} run() in a new thread.
public class Main{
public static void main(String args[]){
MyThread t1 = new MyThread();
[Link]();
}
}
Using Runnable Interface
import [Link].*;
import [Link].*; Create a class that implements
class MyThread implements Runnable{
// Method to start Thread Runnable. Override the run()
public void run(){ method, this contains the code
for the thread. Then create a
String str = "Thread is Running Successfully";
Thread object, pass your
[Link](str);
} Runnable object to it and call
} start().
public class Main{
public static void main(String[] args){
MyThread g1 = new MyThread();
// initializing Thread Object
Thread t1 = new Thread(g1);
// Running Thread
[Link]();
}
}
Running Threads in Java
There are two methods used for running Threads in Java:
● run() Method: Contains the code for the thread. Calling it directly
behaves like a normal method call.
● start() Method: Launches a new thread and internally calls run()
concurrently.
Thread Class constructors
Thread with Sleep() Method
class Demo extends Thread {
public void run() {
for(int i = 1; i <= 5; i++) {
[Link]("Value: " + i);
try {
[Link](1000); // pause 0.5s
} catch (Exception e) {}
}
}
public static void main(String[] args) {
Demo d = new Demo();
[Link]();
}
}
Multiple Threads Running Together
class A extends Thread {
public void run() {
[Link]("Thread A running");
}
}
class B extends Thread {
public void run() {
[Link]("Thread B running");
}
}
public class Test {
public static void main(String[] args) {
A a = new A();
B b = new B();
[Link]();
[Link]();
}
}
Using join() to Wait for Thread Completion
class Worker extends Thread {
public void run() {
[Link]("Worker thread started");
try { [Link](2000); } catch(Exception e){}
[Link]("Worker thread finished");
}
}
public class Main {
public static void main(String[] args) {
Worker w = new Worker();
[Link]();
try {
[Link](); // wait for thread to finish
} catch (Exception e) {}
[Link]("Main thread ends");
}
}
Basic Thread Priority Example
class Job extends Thread {
public void run() {
[Link]("Running: " + [Link]().getName() +
" | Priority: " + [Link]().getPriority());
}
}
public class TestPriority {
public static void main(String[] args) {
Job t1 = new Job();
Job t2 = new Job();
Job t3 = new Job();
[Link]("Low-Priority Thread");
[Link]("Normal-Priority Thread");
[Link]("High-Priority Thread");
[Link](Thread.MIN_PRIORITY); // 1
[Link](Thread.NORM_PRIORITY); // 5
[Link](Thread.MAX_PRIORITY); // 10
[Link]();
[Link]();
[Link]();
}
}
class Task extends Thread {
Task(String name, int p) {
setName(name);
setPriority(p);
}
public void run() {
[Link]("Executing: " + getName() +
" with Priority " + getPriority());
}
}
public class PriorityDemo {
public static void main(String[] args) {
Task t1 = new Task("T1", 3);
Task t2 = new Task("T2", 8);
Task t3 = new Task("T3", 1);
[Link]();
[Link]();
[Link]();
}
}
Basic isAlive() Example
class MyThread extends Thread {
public void run() {
[Link]("Thread Running...");
try { [Link](1000); } catch(Exception e){}
[Link]("Thread Finished.");
}
}
public class AliveDemo {
public static void main(String[] args) throws Exception {
MyThread t = new MyThread();
[Link]("Before start: " + [Link]()); // false
[Link]();
[Link]("After start: " + [Link]()); // true
[Link](); // wait for thread to finish
[Link]("After join: " + [Link]()); // false
}
}