4.1 The Exception Hierarchy
Exception
An exception is an abnormal condition that interrupts normal program execution.
Hierarchy of Exceptions
Object
↓
Throwable
↓
--------------------------------
| |
Error Exception
↓
-------------------
| |
Checked Exception Unchecked Exception
Types of Exceptions
1. Checked Exception
Checked during compile time.
Examples
- IOException
- SQLException
- FileNotFoundException
2. Unchecked Exception
Occurs during runtime.
Examples
- ArithmeticException
- NullPointerException
- ArrayIndexOutOfBoundsException
3. Error
Serious problem not handled by program.
Examples
- StackOverflowError
- OutOfMemoryError
Common Exceptions
| Exception | Cause |
|---|---|
| ArithmeticException | divide by zero |
| NullPointerException | null object access |
| ArrayIndexOutOfBoundsException | invalid array index |
| NumberFormatException | invalid number conversion |
| ClassNotFoundException | class missing |
4.2 Exception Handling Fundamentals
Purpose of Exception Handling
- Prevent abnormal termination
- Maintain normal flow
- Improve reliability
- Handle runtime problems gracefully
try-catch Syntax
try{
// risky code
}
catch(Exception e){
// handling code
}
Example
class Test{
public static void main(String args[]){
try{
int x = 10/0;
}catch(ArithmeticException e){
System.out.println("Cannot divide by zero");
}
System.out.println("Program continues");
}
}
Output
Cannot divide by zero
Program continues
Flow of Exception Handling
try block
↓
Exception occurs?
↓
catch block executes
↓
finally block executes
Multiple catch Blocks
try{
}
catch(ArithmeticException e){
}
catch(ArrayIndexOutOfBoundsException e){
}
catch(Exception e){
}
Specific exception should come before general exception.
Nested try Block
try{
try{
}catch(Exception e){
}
}catch(Exception e){
}
4.3 Throwing, Re-throwing and Catching Exceptions
throw Keyword
Used to manually throw exception.
Syntax
throw new ExceptionType();
Example
class Test{
public static void main(String args[]){
throw new ArithmeticException("Error");
}
}
throws Keyword
Used to declare exception.
Syntax
void show() throws IOException{
}
Example
import java.io.*;
class Test{
static void read() throws IOException{
FileReader f =
new FileReader("a.txt");
}
public static void main(String args[]){
try{
read();
}
catch(IOException e){
System.out.println(e);
}
}
}
Difference Between throw and throws
| throw | throws |
|---|---|
| used inside method | used in method declaration |
| throws exception object | declares exception |
Re-throwing Exception
Exception caught and thrown again.
catch(Exception e){
throw e;
}
4.4 try, catch, throw, throws and finally Keywords
finally Block
finally block always executes whether exception occurs or not.
Syntax
try{
}
catch(Exception e){
}
finally{
}
Example
class Test{
public static void main(String args[]){
try{
int x = 10/0;
}catch(Exception e){
System.out.println("Exception");
}finally{
System.out.println("Finally Block");
}
}
}
Output
Exception
Finally Block
Important Keywords Summary
| Keyword | Purpose |
|---|---|
| try | contains risky code |
| catch | handles exception |
| throw | manually throws exception |
| throws | declares exception |
| finally | always executes |
User Defined Exception
Creating Custom Exception
class MyException extends Exception{
MyException(String msg){
super(msg);
}
}
Using User Defined Exception
class Test{
static void check(int age)
throws MyException{
if(age<18){
throw new MyException(
"Not Eligible");
}
}
public static void main(String args[]){
try{
check(10);
}catch(MyException e){
System.out.println(e);
}
}
}
4.5 Multithreading Fundamentals
Thread
A thread is a lightweight subprocess.
Advantages of Multithreading
- Concurrent execution
- Efficient CPU usage
- Fast execution
- Background task support
Thread Life Cycle
New
↓
Runnable
↓
Running
↓
Blocked/Waiting
↓
Terminated
Ways to Create Thread
- Extending Thread class
- Implementing Runnable interface
4.6 Thread Class and Runnable Interface
1. Extending Thread Class
class MyThread extends Thread{
public void run(){
System.out.println("Thread Running");
}
public static void main(String args[]){
MyThread t = new MyThread();
t.start();
}
}
Important Methods
| Method | Purpose |
|---|---|
| start() | starts thread |
| run() | thread task |
| sleep() | pause thread |
| join() | wait for thread |
| stop() | stops thread |
Difference Between start() and run()
| start() | run() |
|---|---|
| creates new thread | normal method call |
| multithreading occurs | no multithreading |
2. Implementing Runnable Interface
class MyThread implements Runnable{
public void run(){
System.out.println("Running");
}
public static void main(String args[]){
MyThread m = new MyThread();
Thread t = new Thread(m);
t.start();
}
}
Difference Between Thread and Runnable
| Thread Class | Runnable Interface |
|---|---|
| extends Thread | implements Runnable |
| single inheritance limitation | better flexibility |
sleep() Method
Syntax
Thread.sleep(1000);
Pauses thread for milliseconds.
Example of sleep()
class Test extends Thread{
public void run(){
try{
for(int i=1;i<5;i++){
System.out.println(i);
Thread.sleep(1000);
}
}catch(Exception e){
}
}
public static void main(String args[]){
Test t = new Test();
t.start();
}
}
Multithreading Example
class A extends Thread{
public void run(){
for(int i=1;i<=5;i++){
System.out.println("A");
}
}
}
class B extends Thread{
public void run(){
for(int i=1;i<=5;i++){
System.out.println("B");
}
}
}
class Test{
public static void main(String args[]){
A a = new A();
B b = new B();
a.start();
b.start();
}
}
Synchronization
Synchronization prevents multiple threads from accessing shared resource simultaneously.
Syntax
synchronized void show(){
}
Daemon Thread
Background thread providing service to other threads.
t.setDaemon(true);
Main Thread
Every Java program starts with main thread.
Most Important Practical Programs
- try-catch program
- Multiple catch block
- finally block
- throw keyword program
- throws keyword program
- User defined exception
- Thread class program
- Runnable interface program
- sleep() method
- Multithreading example
Most Important Theory Questions
- Define exception.
- Explain exception hierarchy.
- Difference between checked and unchecked exception.
- Explain try-catch-finally.
- Difference between throw and throws.
- What is user defined exception?
- Explain multithreading.
- Difference between Thread and Runnable.
- Difference between start() and run().
- Explain thread life cycle.
Important Viva Questions
Can finally block execute without catch block?
Yes.
Can catch block exist without try block?
No.
Can we have multiple catch blocks?
Yes.
Which block always executes?
finally block.
Can we directly call run()?
Yes, but multithreading will not occur.
Which method starts thread?
start()
Which method contains thread task?
run()
Which exception occurs when dividing by zero?
ArithmeticException
0 comments:
Post a Comment