0% found this document useful (0 votes)
5 views6 pages

Exception-Java

Exception handling in Java allows for managing runtime errors through components like try, catch, finally, throw, and throws. There are two main types of exceptions: checked exceptions, which are checked at compile-time, and unchecked exceptions, which are checked at runtime. Additionally, static methods and blocks are used for class-level operations, while the super keyword is utilized to access parent class methods and constructors.

Uploaded by

ramkumarlaksh74
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
Download as txt, pdf, or txt
0% found this document useful (0 votes)
5 views6 pages

Exception-Java

Exception handling in Java allows for managing runtime errors through components like try, catch, finally, throw, and throws. There are two main types of exceptions: checked exceptions, which are checked at compile-time, and unchecked exceptions, which are checked at runtime. Additionally, static methods and blocks are used for class-level operations, while the super keyword is utilized to access parent class methods and constructors.

Uploaded by

ramkumarlaksh74
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1/ 6

Exception handling in Java is a powerful mechanism that allows you to handle

runtime errors, ensuring that the normal flow of the program is maintained. It
involves the use of several key components, including try, catch, finally, throw,
and throws.

Key Components of Exception Handling

try block: The code that might throw an exception is placed inside a try block.

catch block: This block is used to handle the exception that occurs in the try
block. It is associated with a try block and contains the code that handles the
exception.

finally block: This block contains code that will always be executed, regardless of
whether an exception was thrown or not. It's typically used for cleanup activities,
like closing files or releasing resources.

throw statement: This is used to explicitly throw an exception.

throws keyword: This is used in the method signature to indicate that this method
might throw an exception, and it allows the exception to be propagated to the
calling method.

Types of Java Exceptions


There are mainly two types of exceptions: checked and unchecked. An error is
considered as the unchecked exception. However, according to Oracle, there are
three types of exceptions namely:

Checked Exception
Unchecked Exception

1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and
Error are known as checked exceptions. For example, IOException, SQLException, etc.
Checked exceptions are checked at compile-time.

2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions.
For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.

try {
// Code that might throw an exception
} catch (ExceptionType1 e1) {
// Code to handle ExceptionType1
} catch (ExceptionType2 e2) {
// Code to handle ExceptionType2
} finally {
// Code that will always execute
}

public class ExceptionHandlingExample {


public static void main(String[] args) {
try {
// Code that may throw an exception
int data = 50 / 0; // This will cause ArithmeticException
} catch (ArithmeticException e) {
// Handling the exception
System.out.println("ArithmeticException caught: " + e.getMessage());
} finally {
// Code that will always execute
System.out.println("Finally block is always executed.");
}
}
}

String s=null;
System.out.println(s.length());//NullPointerException

String s="abc";
int i=Integer.parseInt(s);//NumberFormatException

int a[]=new int[5];


a[10]=50; //ArrayIndexOutOfBoundsException

public static void main(String[] args) {

try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}

public static void main(String args[]){


//outer try block
try{
//inner try block 1
try{
System.out.println("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(e);
}

//inner try block 2


try{
int a[]=new int[5];

//assigning the value out of array bounds


a[5]=4;
}

//catch block of inner try block 2


catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}

System.out.println("other statement");
}
//catch block of outer try block
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
}

System.out.println("normal flow..");
}

Finally:

public static void main(String args[]){


try{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e){
System.out.println(e);
}
//executed regardless of exception occurred or not
finally {
System.out.println("finally block is always executed");
}

System.out.println("rest of phe code...");


}

throw Keyword
Purpose: The throw keyword is used to explicitly throw an exception from a method
or a block of code.

Usage: When you want to manually trigger an exception, you use the throw keyword
followed by an instance of an exception class.

Scope: The exception thrown using throw is typically handled using a try-catch
block within the same method or propagated to the calling method.

public class ThrowExample {


public static void checkAge(int age) {
if (age < 18) {
// Throwing an exception using the throw keyword
throw new ArithmeticException("Access denied - You must be at least 18
years old.");
} else {
System.out.println("Access granted - You are old enough!");
}
}

public static void main(String[] args) {


checkAge(15); // This will throw an exception
System.out.println("This line will not execute.");
}
}

throws Keyword
Purpose: The throws keyword is used in the method signature to indicate that the
method might throw one or more exceptions. This serves as a warning to the calling
methods that they need to handle these exceptions.

Usage: When a method can potentially cause an exception that it doesn’t handle
itself, the exception is declared using the throws keyword.

Scope: Exceptions specified by throws are either handled by the calling method (via
a try-catch block) or further propagated up the call stack.

Example in File Handling

3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.

Static Methods
A static method belongs to the class rather than any instance of the class. It can
be called without creating an object of the class. Static methods can access other
static variables and static methods directly but cannot access instance variables
or instance methods directly.

2. Static Block
A static block is a block of code that gets executed when the class is loaded into
memory. It is typically used for initializing static variables or performing
startup activities. Static blocks are executed only once, when the class is first
loaded.

public class StaticExample {

// Static variable
static int count;

// Static block - Executed when the class is loaded


static {
System.out.println("Static block executed.");
count = 10; // Initialize static variable
}

// Static method
static void displayCount() {
System.out.println("Count: " + count);
}
// Instance method
void incrementCount() {
count++; // Modifies static variable
}

public static void main(String[] args) {


// Calling static method without creating an object
StaticExample.displayCount();

// Creating an object of the class


StaticExample obj = new StaticExample();

// Calling instance method to increment the static variable


obj.incrementCount();

// Calling static method again to display the updated count


StaticExample.displayCount();
}
}

Static Block:

The static block is executed when the class StaticExample is loaded into memory,
before any object of the class is created or any static method is called. It is
often used for initializing static variables.
Output: Static block executed.
Static Method (displayCount):

This method can be called directly using the class name without creating an
instance of the class. In the example, displayCount() is called twice to display
the value of the static variable count.
Output:
Count: 10 (Before incrementing)
Count: 11 (After incrementing)

Super:

// Parent class
class Animal {
String name = "Animal";

// Constructor of parent class


Animal() {
System.out.println("Animal constructor called");
}

// Method in parent class


void sound() {
System.out.println("Animal makes a sound");
}
}

// Child class
class Dog extends Animal {
String name = "Dog";

// Constructor of child class


Dog() {
super(); // Calls the parent class constructor
System.out.println("Dog constructor called");
}

// Method in child class


void sound() {
super.sound(); // Calls the parent class method
System.out.println("Dog barks");
}

// Method to display names


void displayNames() {
System.out.println("Name in child class: " + name); // Refers to
child class variable
System.out.println("Name in parent class: " + super.name); // Refers to
parent class variable
}
}

// Main class
public class SuperKeywordExample {
public static void main(String[] args) {
// Creating an object of the child class
Dog dog = new Dog();

// Calling the child class method


dog.sound();

// Displaying names from child and parent class


dog.displayNames();
}
}

You might also like