Java Types and Exception Handling - Advanced Guide

Java Data Types - Detailed

Java me data types do prakar ke hote hain: Primitive aur Non-Primitive (Reference Types).
Primitive types fixed size ke hote hain aur directly variable ke value ko store karte hain.

Primitive Data Types

Data Type Size Default Value Range / Description
byte1 byte0-128 to 127
short2 bytes0-32,768 to 32,767
int4 bytes0-2^31 to 2^31-1
long8 bytes0L-2^63 to 2^63-1
float4 bytes0.0fSingle precision decimal
double8 bytes0.0dDouble precision decimal
char2 bytes'\u0000'Unicode character
boolean1 bitfalsetrue or false

Non-Primitive Data Types

Classes, Interfaces, Arrays, Strings aise types hote hain jinka size fixed nahi hota. Inhe reference types bhi kaha jata hai kyunki variable object ka reference store karta hai, value nahi.

String name = "Rahul";
int[] numbers = {1, 2, 3, 4};
List list = new ArrayList<>();

Java Exception Handling - Detailed Explanation

Exception handling Java me runtime errors ko handle karne ka process hai taaki program crash naa kare. Exception kisi bhi error situation ko refer karta hai jo program ki normal flow ko rokta hai.

Exception Hierarchy Overview

Java ke exceptions do prakar ke hote hain: Checked aur Unchecked (Runtime) exceptions.

java.lang.Throwable
   ├── java.lang.Error
   └── java.lang.Exception
        ├── Checked Exceptions (Compile-time)
        └── Runtime Exceptions (Unchecked)

Checked vs Unchecked Exceptions

Attribute Checked Exceptions Unchecked Exceptions
Handled atCompile timeRuntime
ExamplesIOException, SQLException, ClassNotFoundExceptionArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException
Mandatory handlingYes (try-catch or throws)No

Try-Catch-Finally Example

public class ExceptionDemo {
    public static void main(String[] args) {
        try {
            int a = 50 / 0;  // ArithmeticException
            System.out.println(a);
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero: " + e.getMessage());
        } finally {
            System.out.println("Finally block executed.");
        }
    }
}

Throw & Throws Keywords

throw keyword se manually exception throw kar sakte hain.
throws keyword methods ki declaration me use hota hai taaki caller ko exception handle karna pade.

public void checkAge(int age) throws Exception {
    if (age < 18) {
        throw new Exception("Age must be at least 18");
    }
}

Custom Exception Example

class MyException extends Exception {
    MyException(String message) {
        super(message);
    }
}

public class TestCustomException {
    public static void main(String[] args) {
        try {
            throw new MyException("Custom Exception Occurred!");
        } catch (MyException e) {
            System.out.println(e.getMessage());
        }
    }
}