Professional Documents
Culture Documents
Uncaught Exceptions:- Exceptions that are not handling by the programs called uncaught exceptions.
first we will see stack or call stack. The call stack is the chain of methods that your program executes to get to
the current method. If your program starts in method main() and main() calls method a(), which calls method
b(), which in turn calls method c(), the call stack consists of the following:
c
b
a
main
package test;
public class UncaughtExDemo{
public static void main(String[] args) {
a();
System.out.println("Rest of code");
}
static void a() {
b();
}
static void b() {
int x = 5 / 0; // Can't divide by zero!
// ArithmeticException is thrown here
}
}
Output:-
Exception in thread "main" java.lang.ArithmeticException: / by zero
at test.UncaughtExDemo.b(UncaughtExDemo.java:13)
at test.UncaughtExDemo.a(UncaughtExDemo.java:9)
at test.UncaughtExDemo.main(UncaughtExDemo.java:5)
• An exception that's never caught will cause your application to stop running.
• An exception in the JVM halting and the stack trace will be printed to the output.
Handling Exception:-
package test;
public class CaughtExDemo{
public static void main(String[] args) {
a();
System.out.println("Rest of code");
}
static void a() {
b();
}
static void b() {
try{
int x = 5 / 0; // Can't divide by zero!
// ArithmeticException is thrown here
}
}
catch(ArithmeticException ex){
ex.printStackTrace();
System.out.println(ex.getMessage());
}
}
The throws Keyword:-
If a method does not handle a checked exception, the method must declare it using the throws
keyword.
* It must be use after method declaration ,out side of a method.
package test;
public class ThrowsExDemo{
public static void main(String[] args) {
a();
System.out.println("Rest of code");
}
static void a() {
b();
}
static void b() throws Exception{ // method a() that is caller for b must be handle with
try //catch or throws it.
int x = 5 / 0; // Can't divide by zero!
// ArithmeticException is thrown here
}
}
The throw Keyword:-
Syntax:- throw ThrowbleInstance;
• It must be use inside method body.
public class ThrowDemo{
public static void main(String[] args) {
a();
System.out.println("Rest of code");
}
static void a() {
b();
}
static void b() {
int a=1;
if(a==1){
throw new RuntimeException("The value of a can't be 1");
}}}
Note:- If we want to use the message of RuntimeException in caller function see next example.
public class Student {
public static void main(String[] args) {
a();
System.out.println("Rest of code");
}
static void a() {
try {
b();
} catch (RuntimeException ex) {
System.out.println(ex.getMessage());
}}
static void b() {
int a=1;
if(a==1){
throw new RuntimeException("The value of a can't be 1");
}}}