The Best Technical Blog Ever

twitterrss

Exception Handling in java

Before we take a look at how to handle the exceptions, first you need to understand what do we mean by an exception. Exception is an error that can occur in different situations like wrong/invalid data entered by user, file that needs to be opened cannot be found, Operands being manipulated are out of ranges, stack overflow exception, when an application requires larger memory than the available memory, hardware failure, network connection failure, Database server down, etc.


In this chapter, we will discuss java exceptions, its type and how to handle these exceptions using the exception handler components with various examples , which will teach you everything you need to know to get started with Java exceptions.


What is an Exception?

When an error occurs at runtime, an exception is thrown. It is possible for an application to catch this exception and recover from it. Exceptions are thrown by the programming code during the execution of programs to notify the unusual situation / an error that interrupts the normal flow of instructions. For example, if you are trying to divide any number by zero, then the code responsible for this calculation will detect this and will throw an exception with the appropriate error message like divide by zero exception.


Every exception is either a checked exception or an unchecked exception. Exceptions can be built-in (defined in Java's standard libraries) or user-defined. Here are some examples of built-in exceptions.


  • ArithmeticException
  • NullPointerException
  • IndexOutOfBoundsException
  • FileNotFoundException

Built-in Exceptions in java:

The java.lang package in java defines several exception classes. Here, mostly used( general) Exception classes are subclasses of the standard type RuntimeException. These unchecked exceptions need not be included in any method's throws list because the compiler does not verify whether a method handles or throws these exceptions.


But checked exceptions defined by java.lang should be included in a method's throws list. In addition to the exceptions in java.lang, Java defines some more exceptions that relate to its other standard packages.


Java's Unchecked RuntimeExceptions Defined in java.lang:
Sl.No Exceptions Description
1 ArithmeticException Arithmetic error, such as divide- by - zero.
Example: int a=22/0;
2 ArrayIndexOutOfBoundsException Thrown to indicate that an array has been accessed with an wrong index(out of range). The index is either negative or greater than or equal to the size of the array.
Example:int a[]=new int[5];
	a[30]=25;
3 ArrayStoreException attempting to store the wrong type of object into an array of objects.(storing a wrong type of data in an array).
Example:
 Object[] a = new Integer[6];
//12.8 is not an integer
 a[0] = 12.8;
 Object[] x = new String[4];
//try to store an array of objects
 x[0] = new Object[5];
4 ClassCastException Invalid cast.(i.e) attempting to cast a specific object to a class of which it is not an instance. For example, an Integer object cannot be casted to a String object.
Example:
Object a = new Integer(50);
System.out.println((String)a);
5 EnumConstantnotPresentException Trying to use an undefined enumeration value. This Exception thrown when an application tries to access an enum constant by name and the enum type contains no constant with the specified name.
6 IllegalArgumentException Thrown to indicate that a method has been passed an illegal or inappropriate argument.
7 IllegalMonitorStateException Illegal Monitor operations, such as waiting on an unlocked thread.
8 IllegalStateException Thrown to indicate the java environment or Java application is not in an appropriate state for the requested operation.
9 IllegalThreadStateException Thrown to indicate that a thread is not in an appropriate state for the requested operation for example, the suspend and resume methods in class Thread.
10 IndexOutOfBoundsException Thrown to indicate that an index is out of range (to an array, to a string, or to a vector).
11 NegativeArraySizeException Array created with a negative size.
12 NullPointerException invalid use of a null reference. Thrown when performing any operation by the variable with null value.
Example:
String str1=null;
System.out.println(str1.length());
13 NumberFormatException Invalid conversion of a string to a numeric format.
Example:
String s="Solsoftsys";
int x=Integer.parseInt(s);
14 Security Exception Attempt to violate security.
15 StringIndexOutOfBounds Thrown to indicate that an index is either negative or greater than the size of the string.
16 TypeNotPresentException Thrown when an application tries to access a type using a string representing the type's name, but no definition for the type with the specified name can be found.
17 UnsupportedOpperationException Thrown to indicate that the requested operation is not supported.


Java's Checked Exceptions Defined in java.lang:
Sl.No Exceptions Description
1 ClassNotFoundException class not found.
2 CloneNotSupportedException Thrown to indicate that the clone method in class Object has been called to clone an object, but that the object's class does not implement the Cloneable interface.
3 IllegalAccessException Thrown to indicate the access to a class is denied.
4 InstantiationException Thrown when an application tries to create an object of an abstract class or interface.
5 InterruptedException Thrown when a thread is interrupted by another thread.
Example:
if (Thread.interrupted())
  throw new InterruptedException();
  // Clears interrupted status!
6 NoSuchFieldException indicates that the class doesn't have a field of a specified name.
7 NoSuchMethodException Thrown when a particular method cannot be found.
8 ReflectiveOperationException Common superclass of exceptions thrown by reflective operations in core reflection.


Java's Common Errors:
Sl.No Errors Description
1 AssertionError Thrown to indicate that an assertion failed.
2 ExceptionInInitializeError Thrown to indicate an unexpected exception in a static initializer.
3 VirtualMachineError Thrown to indicate a problem with the JVM.
4 OutOfMemoryError Thrown when there is no more memory available to allocate an object or perform garbage collection.
5 NoClassDefFoundError Thrown when the JVM cannot find a class definition that was found at compile time.
6 StackOverflowError Thrown to indicate that a stack overflow occurs.

Keypoints to remember in java

1. Java is a high level, robust, secured , platform independent and object oriented programming.... more info

Back to Basics:- Java Syntax

In this session, you are going to refresh some basic set of rules(java syntax), defining how a ... more info

Total Visits
Traffic feed status