Exception-Java
Exception-Java
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.
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.
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.
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
}
String s=null;
System.out.println(s.length());//NullPointerException
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
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");
}
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:
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.
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.
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.
// Static variable
static int count;
// Static method
static void displayCount() {
System.out.println("Count: " + count);
}
// Instance method
void incrementCount() {
count++; // Modifies static variable
}
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";
// Child class
class Dog extends Animal {
String name = "Dog";
// Main class
public class SuperKeywordExample {
public static void main(String[] args) {
// Creating an object of the child class
Dog dog = new Dog();