An exception is an unwanted or unexpected event that occurs during the execution of the program that disrupts the normal flow.
class Test
{
public static void main(String[] args)
{
System.out.println("1");
System.out.println("2");
System.out.println("3");
System.out.println("4");
System.out.println("5");
System.out.println(10/0);
System.out.println("6");
System.out.println("7");
}
}
Output is printed only upto 5 and an arithmetic exception is shown
Difference between exception and error
Hierarchy of Exception
There are two types of exceptions in Java
Checked exception/Compile time exception
Unchecked exception/Run time exception
Exception keywords in Java
Whenever there is an exception, the method in which it occurs will create an object with the following properties:
exception name
description
stack trace
We can get the exception as output using
e.printStackTrace();
prints exception name, stack trace and description
SOP(e); // SOP(e.toString());
prints exception name and description
SOP(e.getMessage());
prints only decription
1. Try catch
//syntax
try
{
//risky code
}
catch(ExceptionClassName ref.var.name)
{
//handling code
}
class Test
{
public static void main(String[] args)
{
try
{
int a=10,b=0,c;
c=a/b;
}
catch(Exception e)
{
System.out.println(e);
}
}
}
2. Finally
Finally is the block that is always executed whether an exception is handled or not
class Test
{
public static void main(String[] args)
{
try
{
int a=10,b=0,c;
c=a/b;
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block");
}
}
}
3. Throw
public class Main {
static void checkAge(int age) {
if (age < 18) {
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); // Set age to 15 (which is below 18...)
}
}
4. Throws
public class Main {
static void checkAge(int age) throws ArithmeticException {
if (age < 18) {
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); // Set age to 15 (which is below 18...)
}
}