Exception handling in java
Exception handling:- Exception is an abnormal condition that occurs in a program at runtime. Generally it terminates the program. Few conditions that raises an exception are divide by zero, file not found, number format exception, array out of bound exception
Exception handling:-
Exception is an abnormal condition that occurs in a program at runtime.
Generally it terminates the program. Few conditions that raises an exception are divide by zero, file not found, number format exception, array out of bound exception
try block
It is used to write the code, which might throw an exception. There can be any number of try blocks in a program.
catch block:-
It is used to write the statements which are supposed to be executed if an exception is thrown. One try block can have more than one catch blocks.
It takes an object of an exception class as an argument
throw keyword:-
It is used to explicitly throw an object of an exception class.
throws keyword:-
It is used to declare that a particular function will not handle any exceptions occurred, and tells the compiler to handle the exceptions on it's own.
Basically it re throws an exception.
finally block:-
It is used to write the statements that are compulsory to execute even if the exception is thrown or not.
This should be the last block in the code.
The syntax of try catch and finally is :
try {
// code
} catch (ExceptionType e) {
// catch block
}catch (ExceptionType e) {
// catch block
}catch (ExceptionType e) {
// catch block
} finally {
// finally block
}Example code to understand exception handling in java.
Class Exception_Demo
{
public static void main()
{
try
{
int a =4, b=0;
int div=a/b;
system.out.println(div);
}
catch( ArithmeticException e)
{
system.out.println("for divide by zero this will execute");
}
catch(Exception e)
{
system.out.println("for any other exception this will execute");
}
finally
{
system.out.println("In finally");
}
}
}Related Posts
Continue learning with these related articles

Logic Gates for ISC Class 11: Truth Tables, Universal Gates, Half and Full Adder
ISC Class 11 Computer Science notes on logic gates: AND, OR, NOT, NAND, NOR, XOR and XNOR with truth tables, why NAND and NOR are universal gates, and half adder and full adder circuits with their Boolean expressions.
Decimal to Binary Conversion in Java: 3 Programs with Examples
How to convert a decimal number to binary on paper and in Java: three programs (String, place value and Integer.toBinaryString), binary to decimal, a dry run and common mistakes.
Sum of First n Natural Numbers in Java (Loop and Formula)
Find the sum of the first n natural numbers in Java with a for loop, a while loop and the formula n(n + 1)/2, with a dry run and the sums of even numbers, odd numbers, squares and cubes.