Exception Handling
Sometimes, while executing programs, we get errors that influence the normal working of the program. Such errors are called exceptions and the method used to deal with these exceptions is known as exception handling.
Exceptions are of two types:
- Built-in exception
- User-defined exception
Built-in exceptions are available in Java libraries. These predefined exceptions can be used to explain certain error situations.
Users can also create their own exception class and throw that exception using the throw
keyword. These exceptions are known as user-defined or custom exceptions.
A. Exception Keywords:
Exception handling is done with the help of these keywords:
try
: The try block is always accompanied by a catch or finally block. The try block is where the exception is generated.catch
: The catch block handles the exception that is generated in the try block.finally
: Finally is always executed whether there is an exception or not.throw
: It is used to throw a single exception.throws
: It declares which type of exception might occur.
B. Examples:
a. try...catch:
public class TryCatch {
public static void main(String[] args) {
try {
int result = 36/0;
} catch(ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Output:
Error: / by zero
b. multiple catch:
public class MultipleCatch {
public static void main(String[] args) {
try {
int result = 36/0;
} catch(NullPointerException e1) {
System.out.println("Error: " + e1.getMessage());
} catch(ArithmeticException e2) {
System.out.println("Error: " + e2.getMessage());
}
}
}
Output:
Error: / by zero
c. try...finally:
public class TryFinally {
public static void main(String[] args) {
try {
int result = 36/0;
} finally {
int result = 36/6;
System.out.println("Finally block result:" + result);
}
}
}
Output:
Finally block result:6
Exception in thread "main" java.lang.ArithmeticException: / by zero
at javaFiles/ExceptionHandling.TryFinally.main(TryFinally.java:6)
d. try...catch...finally:
public class TryCatchFinally {
public static void main(String[] args) {
try {
int result = 36/0;
} catch(ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
int result = 36/6;
System.out.println("Finally block result:" + result);
}
}
}
Output:
Error: / by zero
Finally block result:6
e. throws:
public class Throws {
public static void example() throws ArithmeticException {
int result = 36/0;
}
public static void main(String[] args) {
try {
example();
} catch (ArithmeticException e) {
System.out.println(e);
}
}
}
Output:
java.lang.ArithmeticException: / by zero
f. throw keyword:
public class Throw {
public static void example() {
throw new ArithmeticException("divide by 0");
}
public static void main(String[] args) {
example();
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: divide by 0
at javaFiles/ExceptionHandling.Throw.example(Throw.java:5)
at javaFiles/ExceptionHandling.Throw.main(Throw.java:9)