What is an exception?
- An Exception is an unwanted event that interrupts the normal flow of the program.
- When an exception occurs program execution gets terminated. In such cases, we get a system generated error message. The good thing about exceptions is that they can be handled in Java. By handling the exceptions we can provide a meaningful message to the user about the issue rather than a system generated message, which may not be understandable to a user.
Why an exception occurs?
- Opening a non-existing file in your program.
- Network connection problem.
- Invalid input data provided by user.
- Accessing array index out of range.
Advantage of Exception Handling
- Ensures that the flow of the program doesn’t break when an exception occurs.
Examples
NullPointerException
ArithmeticException
ArrayIndexOutOfBoundsException
Types of exceptions
- Checked exceptions
- Unchecked exceptions
- Error
Checked exceptions
- All exceptions other than Runtime Exceptions are known as checked exceptions.
- Compiler checks them during compilation to see whether the programmer has handled them or not.
- If these exceptions are not handled/declared in the program, you will get compilation error.
Examples of Checked Exceptions
SQLException
IOException
ClassNotFoundException
Unchecked exceptions
- Runtime Exceptions are also known as Unchecked Exceptions.
- These exceptions are not checked at compile-time so compiler does not check whether the programmer has handled them or not but it’s the responsibility of the programmer to handle these exceptions
Examples of Unchecked Exceptions
ArithmeticException
NullPointerException
ArrayIndexOutOfBoundsException
Error
- Error is irrecoverable and which is out of programmer’s control.
Examples of Error
OutOfMemoryError
VirtualMachineError
AssertionError
Keyword | Description |
---|---|
try |
The “try” keyword is used to specify a block where we should place exception code. The try block must be followed by either catch or finally. It means, we can’t use try block alone. |
catch |
The “catch” block is used to handle the exception. It must be preceded by try block which means we can’t use catch block alone. It can be followed by finally block later. |
finally |
The “finally” block is used to execute the important code of the program. It is executed whether an exception is handled or not. |
throw |
The “throw” keyword is used to throw an exception. |
throws |
The “throws” keyword is used to declare exceptions. It doesn’t throw an exception. It specifies that there may occur an exception in the method. It is always used with method signature. |
Example
public class ExceptionExample {
public static void main(String args[]) {
try {
int data = 100 / 0; // code that may raise exception
} catch (ArithmeticException e) {
System.out.println(e);
}
System.out.println("rest of the code...");
}
}
Output
java.lang.ArithmeticException: / by zero
rest of the code...
Common Scenarios of Java Exceptions
int a = 50 / 0; // ArithmeticException
String s = null;
System.out.println(s.length()); // NullPointerException
s = "abc";
int i = Integer.parseInt(s); // NumberFormatException
int array[] = new int[5];
array[10] = 50; // ArrayIndexOutOfBoundsException
try
- Java try block is used to enclose the code that might throw an exception. It must be used within the method.
- If an exception occurs at the particular statement of try block, the rest of the block code will not execute. So, it is recommended not to keeping the code in try block that will not throw an exception.
- Java try block must be followed by either catch or finally block.
Syntax of Java try-catch
try {
// code that may throw an exception
} catch (Exception e) {
// Exception handling logic
}
Syntax of try-finally block
try {
// code that may throw an exception
} finally {
// this block will execute irrespective of exception
}
catch
- Java catch block is used to handle the Exception by declaring the type of exception within the parameter. The declared exception must be the parent class exception ( i.e., Exception) or the generated exception type. However, the good approach is to declare the generated type of exception.
- The catch block must be used after the try block only. You can use multiple catch block with a single try block.
- If an exception occurs in the try block, the rest of the block code will not execute.
- we can handle the exception using the parent class exception.
Multi-catch block
- A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler.
- At a time only one exception occurs and at a time only one catch block is executed.
- All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must come before catch for Exception.
Example on Multi-catch block
public class ExceptionExample {
public static void main(String[] args) {
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");
}
}
What would be the output?
public static void main(String[] args) {
try {
String s = null;
System.out.println(s.length());
} 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");
}
}
What would be the output?
public static void main(String args[]) {
try {
int a[] = new int[5];
a[5] = 30 / 0;
} catch (Exception e) {
System.out.println("common task completed");
} catch (ArithmeticException e) {
System.out.println("task1 is completed");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("task 2 completed");
}
}
finally
- Java finally block is a block that is used to execute important code such as closing connection, stream etc.
- Java finally block is always executed whether exception is handled or not.
- Java finally block follows try or catch block.
What would be the output?
public static void main(String args[]) {
try {
int data = 25 / 5;
System.out.println(data);
} catch (NullPointerException e) {
System.out.println(e);
} finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
What would be the output?
public static void main(String args[]) {
try {
int data = 25 / 0;
System.out.println(data);
} catch (NullPointerException e) {
System.out.println(e);
} finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
What would be the output?
public static void main(String args[]) {
try {
int data = 25 / 0;
System.out.println(data);
} catch (ArithmeticException e) {
System.out.println(e);
} finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
NOTE
- For each try block there can be zero or more catch blocks, but only one finally block.
- The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).