exception and error in java code example
Example 1: error vs exception
Both Error and Exception are derived from Throwable in Java.
Error represents errors which are generally cannot be handled. For examples:
OutOfMemoryError, NoClassDefFoundError
Exception represents errors which can be caught and handled. For examples:
IOException, NullPointerException
Exception is divided in two categories; checked and unchecked Exception.
Checked Exception require a mandatory try-catch code block to handle it.
Unchecked Exception mostly represent programming errors (NullPointerException
or RuntimeException)
Errors are unchecked exception and the developer is not required
to do anything with these.
All the Errors are Exceptions, but the reverse is not true.
In general Errors are which nobody can control or guess when it happened,
on the other hand Exception can be guessed and can be handled.
Example 2: what is exception in java
In java exception is an object. Exceptions are created when an abnormal
situations are arised in our program. Exceptions can be created by JVM or
by our application code. All Exception classes are defined in java.lang.
In otherwords we can say Exception as run time error.
Example 3: exception in java
In java exception is an object. Exceptions are created when an abnormal
situations are arised in our program. Exceptions can be created by JVM or
by our application code. All Exception classes are defined in java.lang.
In otherwords we can say Exception as run time error. I use try & catch blocks
to handle any exceptions in my code.
I am familiar with major checked and unchecked exceptions and
handle it accordingly to make my code execution smooth
Example 4: exception handling in java example
public class Exception8 {
public static void main(String[]args)
{
fun1();
fun2();
}
static void fun1()
{
fun3();
}
static void fun2()
{
fun3();
}
static void fun3()
{
try {
System.out.println(20/0);
}
catch(ArithmeticException e)
{
System.out.println("Zero divison ");
}
}
}
Example 5: exception java
1.Unchecked: occurs during run time
2.Checked Exceptions:occurs during the compile time.
needs to be handled IMMEDIATELY
Exception handling: try & catch: blocks, used for handling the exception
throws keyword is used within the method signature
disadvantage is: throws keyword whoever calls the method
will have to handle the exception again but with
try/catch you handle once. Try/catch is better way to handle it
in utility class. Next time you call method you don’t get any exceptions
most common Exception like NullPointerExceptio,
ArrayIndexOutOfBound, ClassNotFoundException, IOException.
are unchecked and they are descended from java.lang.RuntimeException
In Selenium: nosuchelement, nostaleexception, nosuchaframe
In SQL: SQL exception