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

ISC Practical 2027: College Enrolment Code Validator and Stream Report – Algorithm and Java Program
Fully solved ISC Computer Science Practical 2027 question: validate college enrolment codes made of a stream, year and serial number, give the exact reason for each rejection, auto-correct lowercase streams and prepare a stream-wise report.

ISC Practical 2027: Digital Lock Security Code Analyzer – Algorithm and Java Program
Fully solved ISC Computer Science Practical 2027 number-logic question: for a 5 to 10 digit security code, find the first and last digits, odd and even position sums, product of non-zero digits, digit frequency and classify the code as STRONG, MODERATE or WEAK.

String Methods in Java for ICSE Class 10: 25 Output Questions with Answers
ICSE Class 10 Computer Applications practice on String class methods: length, charAt, indexOf, lastIndexOf, substring, replace, trim, compareTo, equals and more, with 25 board-style output questions and step-by-step answers.