Syntax of throws keyword:
void method_name() throws exception_class_name{
...
}
Which exception should we declare?
checked exception only, because:
Program which describes that checked exceptions can be propagated by throws keyword.
import java.io.IOException;
class Simple{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Simple obj=new Simple();
obj.p();
System.out.println("normal flow...");
}
}
Rule: If you are calling a method that declares an exception, you must either caught or declare the exception.
There are two cases:
Case1: You handle the exception
In case you handle the exception, the code will be executed fine whether exception occurs during the program or not.
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
class Test{
public static void main(String args[]){
try{
Test t=new Test();
t.method();
}catch(Exception e){System.out.println("exception handled");}
System.out.println("normal flow...");
}
}
Case 2: You declare the exception
A)Program if exception does not occur
import java.io.*;
class M{
void method()throws IOException{
System.out.println("device operation performed");
}
}
class Test{
public static void main(String args[])throws IOException{//declare exception
Test t=new Test();
t.method();
System.out.println("normal flow...");
}
}
B)Program if exception occurs
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
class Test{
public static void main(String args[])throws IOException{//declare exception
Test t=new Test();
t.method();
System.out.println("normal flow...");
}
}
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…