Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can we throw an Unchecked Exception from a static block in java?
A static block is a block of code with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading.
Example
public class MyClass {
static{
System.out.println("Hello this is a static block");
}
public static void main(String args[]){
System.out.println("This is main method");
}
}
Output
Hello this is a static block This is main method
Exceptions in static block
Just like any other method in Java when an exception occurs in static block you can handle it using try-catch pair.
Example
import java.io.File;
import java.util.Scanner;
public class ThrowingExceptions{
static String path = "D://sample.txt";
static {
try {
Scanner sc = new Scanner(new File(path));
StringBuffer sb = new StringBuffer();
sb.append(sc.nextLine());
String data = sb.toString();
System.out.println(data);
} catch(Exception ex) {
System.out.println("");
}
}
public static void main(String args[]) {
}
}
Output
This is a sample fileThis is main method
Throwing exceptions in static block
Whenever you throw a checked exception you need to handle it in the current method or, you can throw (postpone) it to the calling method.
You cannot use throws keyword with a static block, and more over a static block is invoked at compile time (at the time of class loading) no method invokes it.
Herefore, if you throw an exception using the throw keyword in a static block you must wrap it within try-catch blocks else a compile time error will be generated.
Example
import java.io.FileNotFoundException;
public class ThrowingExceptions{
static String path = "D://sample.txt";
static {
FileNotFoundException ex = new FileNotFoundException();
throw ex;
}
public static void main(String args[]) {
}
}
Compile time error
ThrowingExceptions.java:4: error: initializer must be able to complete normally
static {
^
ThrowingExceptions.java:6: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
throw ex;
^
2 errorsAdvertisements