Exeception handeling

During the execution of your program, it may experience abnormal or exceptional conditions. As a result of these, the system may crash. An exception may occur due to several reasons. Some of these include:

  • A file that needs to be opened can’t be found.
  • A client has entered invalid information.
  • A system association has been lost amidst correspondences, or the JVM has used up all the available memory.

Some of these exceptional cases are created by client mistake, others by developer blunder, and others by physical assets that have fizzled into your code in some way. To see how exception handling works in Java, you have to comprehend the three classifications of exceptions:

  • Errors:

    These are not exceptional cases whatsoever. Therefore, errors can be defined as issues that are beyond the understanding and the ability to control of the client or the software engineer. They are usually overlooked in your code on the grounds that you can once in a while take care of a mistake. Case in point, if a stack overflow happens, it is sure to result in an error. They are additionally disregarded at the time of compiling.

  • Runtime Exceptions:

    It is a particular case that most likely could have been dodged by the software engineer. Runtime exceptions are disregarded at the time of assemblage.

  • Checked Exceptions:

    It is a special case that is regularly a client mistake or an issue that can’t be predicted by the developer. Case in point, if a file is to be opened, yet the file can’t be found, an exception of this type happens. These exceptional cases can’t just be disregarded at the time of compilation and dry runs.

Hierarchy of Exceptions

All classes of exceptions are subtypes of the java.lang.exception class. This class is a subclass of the Throwable class. Other than the exception class, there is an alternate subclass called Error which is gotten from the Throwable class. These special case scenarios are not ordinarily caught by the Java programs. These conditions ordinarily happen if alternative methods are not taken care of by the java programs. Errors are produced to demonstrate lapses created by the runtime environment. A sample exception is: Out of Memory or Stack Overflow.

The Exception class has two primary subclasses: IOException and RuntimeException Classes.

Exception Methods:

Here is a list of methods that are available as part of the Throwable class.

  • public Throwable getcause()

    This method gives back the cause of the exemption as mentioned by a Throwable item.

  • public String getmessage()

    This method gives back the exception’s complete message and details. This message is usually included in the Throwable constructor.

  • public void printstacktrace()

    This method prints the aftereffect of tostring() alongside the stack follow to System.err, the output stream for error.

  • public String tostring()

    The method gives back where its due of the class linked with the aftereffect of getmessage()

  • public Throwable fillinstacktrace()

    The method fills the stack of this Throwable object with the current trace of the stack, adding to any past data in the trace of the stack.

  • public Stacktraceelement [] getstacktrace()

    The method gives back an array containing every component on the trace of the stack. The component at file 0 speaks to the highest point of the call stack, and the last component in the show speaks to the system at the base of the call stack.

Getting Exceptions:

A system discovers a special case utilizing a blend of the try and catch keywords. A try scope is set around the code that may produce an exemption. Code inside this scope is alluded to as secured code, and the structure for utilizing try/catch is given below:

Syntax
		try {
		//Code that may produce an exception
		}catch(nameofexception exp_1) {
		//Code to be executed once an exception occurs
		}

A try block includes announcing the kind of exception you are attempting to get. If an exception happens in ensured code, the catch square that executes after the attempt is checked. In the event that this sort of special case that happened in a try block, the exception goes to the catch block, which is also passed as a system parameter.

Example
		public class MyException{
		public static void main(string args[]){
		try{
		int myarr[] = new int[2];
		System.out.println(“This statement attempts to access the third element of the array:” +a[3]);
		}catch(arrayindexoutofboundsexception e_1){
		System.out.println(“The thrown exception is: ” + e_1);
		}
		System.out.println(“Exception: Out of Bounds”);
		}

This would deliver the accompanying result:

The thrown exception is: java.lang.arrayindexoutofboundsexception: 3

Execution: Out of Bounds

Using Multiple Try Blocks

A single piece of code can have several catch blocks for catching different exceptions. The structure of the multiple try/catch blocks is given below:

Syntax
		try {
		//Statements to be tested
		}catch(exceptiontype1 e_1) {
		//Catch block 1
		}
		catch(exceptiontype2 e_2) {
		//Catch block 2
		}catch(exceptiontype3 e_3) {
		//Catch block 3
		}

This code uses three catches. However, you can use as many catch blocks as you need for your code. On the off chance that an exception happens in the protected code, the exemption is thrown and caught firstly by the first catch block. If the exception type matches, then the catch block executes. However, if the exception type doesn’t match, the exception is open to be caught by the next catch block. This process continues until a matching exception type is found or all the catch blocks have been checked.

Example
		try{
		filex = new Fileinputstream(nameoffile);
		num = (byte) filex.read();
		}catch(IOException e_1) {
		e_1.printstacktrace();
		return -1;
		}catch(filenotfoundexception f_1){
		f_1.printstacktrace();
		return -1;
		}

A try block includes announcing the kind of exception you are attempting to get. If an exception happens in ensured code, the catch square that executes after the attempt is checked. If this sort of particular case that occured in a try block, the exception goes to the catch block, which is also passed as a system parameter.

		public class MyException{
		public static void main(string args[]){
		try{
		int myarr[] = new int[2];
		System.out.println(“This statement attempts to access the third 
		element of the array:” +
		a[3]);
		}catch(arrayindexoutofboundsexception e_1){
		System.out.println(“The thrown exception is: ” + e_1);
		}
		System.out.println(“Exception: Out of Bounds”);
		}

This would deliver the accompanying result:

The thrown exception is: java.lang.arrayindexoutofboundsexception: 3

Exception: Out of Bounds

Using Multiple Try Blocks

A single piece of code can have several catch blocks for catching different exceptions. The structure of the multiple try/catch blocks is given below:

Syntax
		try {
		//Statements to be tested
		}catch(exceptiontype1 e_1) {
		//Catch block 1
		}
		catch(exceptiontype2 e_2) {
		//Catch block 2
		}catch(exceptiontype3 e_3) {
		//Catch block 3
		}

This code uses three catches. However, you can use as many catch blocks as you need for your code. On the off chance that an exception happens in the protected code, the exemption is thrown and caught firstly by the first catch block. If the exception type matches, then the catch block executes. However, if the exception type doesn’t match, the exception is open to be caught by the next catch block. This process continues until a matching exception type is found or all the catch blocks have been checked.

		try{
		filex = new Fileinputstream(nameoffile);
		num = (byte) filex.read();
		}catch(IOException e_1) {
		e_1.printstacktrace();
		return -1;
		}catch(filenotfoundexception f_1){
		f_1.printstacktrace();
		return -1;
		}
Common Exceptions

In Java, it is conceivable to characterize two categories of Exceptions and Errors.

  • Programmatic exceptions: – These exceptional cases are tossed unequivocally by the application or the API software engineers Examples: Illegalargumentexception, IllegalStateException.
  • JVM Exceptions: – These are exemptions/mistakes that are solely or consistently thrown by the JVM. Some exceptions of this class are ArrayIndexOutOfBoundsException, NullPointerException and ClassCastException.

Copyright 1999- Ducat Creative, All rights reserved.