In Java we have two types of Exceptions, those are checked and unchecked exceptions. Usually checked exceptions can be handled by using the try and catch block in the application code. In the other hand unchecked exceptions occurs during the Runtime of a java application.
Exception is nothing but an error or an event occurred during the execution of a Java application, which eventually causes an application to exit or behaves differently during its execution.
There are two types of exceptions in Java
Checked Exceptions can be handled via application code using the try and catch block, all these exceptions are derived from the class java.lang.Exception.
In the other hand unchecked exceptions cannot be handled 100% via application code but through an extra code can minimize these exceptions. All unchecked exceptions are derived from the java.lang.RuntimeException.
Example : java.lang.NullPointerException
NullPointerException can happen while calling a method or function through a null reference Object,this can be avoided by checking the null reference but this is an extra overhead for the developers
public class CheckedExceptionHandling { public static void main(String[] args) { try { // Check whether given password contains specified length or not otherwise throw // an exception. String password = "abc123"; if (password.length() >= 8) { System.out.println("Password Contains specified length"); } else { throw new Exception("password should contain a minimum length of 8"); } } catch (Exception e) { System.out.println("Password Length Exception : "+ e.getMessage()); e.printStackTrace(); } } }
When you execute the above program, you'll get the below output.
output :Password Length Exception : password should contain a minimum length of 8 java.lang.Exception: password should contain a minimum length of 8 at CheckedExceptionHandling.main(CheckedExceptionHandling.java:12)
public class UnCheckedException { public static void main(String[] args) { // Check whether given password contains specified length or not otherwise throw // an exception. String password = "abc123"; if (password.length() >= 8) { System.out.println("Password Contains specified length"); } else { throw new RuntimeException("password should contain a minimum length of 8"); } } }
When you execute the above program, you'll get the below output.
output :Exception in thread "main" java.lang.RuntimeException: password should contain a minimum length of 8 at UnCheckedException.main(UnCheckedException.java:11)