Exception Handling
Exception Handling
3. Handling Exceptions
Java uses a try-catch block to handle exceptions. If an exception occurs
within a try block, it is caught by the corresponding catch block. If no
exception occurs, the catch block is skipped.
Syntax:
java
Copy code
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
} finally {
// Code that will always execute, whether or not an exception occurs
}
Example:
java
Copy code
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0; // Will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
} finally {
System.out.println("Execution complete.");
}
}
}
In this example, the ArithmeticException is caught by the catch block, and
the finally block is always executed, regardless of whether an exception
occurs.
4. Throwing Exceptions
You can explicitly throw exceptions using the throw keyword. This is useful
when you want to create your own custom exception or handle specific
conditions in a program.
Example:
java
Copy code
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
5. Types of Exceptions
Checked Exceptions: These are exceptions that must be caught or
declared in the method. Example:
java
Copy code
try {
FileInputStream file = new FileInputStream("test.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Unchecked Exceptions: These are runtime exceptions that do not
need to be caught or declared. Example:
java
Copy code
public class Main {
public static void main(String[] args) {
int[] arr = new int[5];
System.out.println(arr[10]); // Throws
ArrayIndexOutOfBoundsException
}
}
6. Multithreading in Java
Multithreading is the capability of executing multiple threads
simultaneously. A thread is a lightweight process, and Java's built-in
threading mechanism allows you to perform multiple tasks concurrently,
improving the efficiency of your program.
9. Thread Synchronization
When multiple threads access shared resources, they can lead to data
inconsistency. Synchronization ensures that only one thread accesses a
resource at a time, preventing conflicts.
Synchronized Methods: Declaring a method as synchronized
ensures that only one thread can execute it at a time.
Example:
java
Copy code
class Counter {
private int count = 0;
MyThread(Counter counter) {
this.counter = counter;
}
thread1.start();
thread2.start();
thread1.join();
thread2.join();