Exception Handling Tutorials in Java

0
170
Spread the love
  • 59
  • 85
  • 26
  • 89
  •  
  •  
  •  
  • 14
  •  
  •  
    273
    Shares

In order to deal with simple errors that are likely to occur only in individual methods, try not to create an exception class. we can use an if statement in most cases to trap these types of errors.

Lets look into an example:

try{
System.out.println (myString.toString ();
}
catch (NullPointerException e){
System.out.println ("myString is null!");
}

In this case it is a overkill for the Exception handling. The simpler form would be:

if (myString! = null){
System.out.println (myString.toString ();
}
else
System.out.println ("myString is null");
}

When we will not catch an exception or throw exceptions?

When we call any method that throws a checked exception, we must either throw the exception or catch it. If we decide that we can not handle the exception in the method where it occurs, write a throw statement to send the exception up to the calling method, which must then either handle it with an exception handler, or throw it up to its calling method.

The following set of examples show how we must either catch or throw a checked exception, in order to avoid compiler errors.

The first example shows code that throws an IOException. The statement in the method getFileLength may throw an IO exception when it calls the constructor of the RandomAccessFile class.

In addition, the statement that calls the length method of the RandomAccessFile object may also throw an IOException. we so specify the throws clause in the declaration for the getFileLength method to trap IOException.Lets see exception handling in java with examples

public static long getFileLength () throws IOException{
RandomAccessFile in = new RandomAccessFile ("mytext.dat", "r");
long length = in.length ();
return length;
}

Our next example shows code for a method that calls the getFileLength method. Since we already know that the getFileLength method call throws an IOException error, our new method must either handle the IO Exception or throw it. Our example here shows how to handle the IOException by catching it with a try statement: Lets see exception handling in java with examples-

public static int getRecordCount(){
try{
long length = getFileLength(); // this may throw an IOException
int recordCount = (int) (length / /RECORD_SIZE);
return recordCount;
}
catch (IOException e) // this will catch the IOException
{
System.out.println("IO Exception!");
return 0;
}
}

The next example shows how a method can call the getFileLength method without catching IOException. Instead, it throws the exception. Lets see exception handling in java with examples-

public static int getRecordCount() throws IOException
{
long length = getFileLength(); //this may throw an IOException
int recordCount = (int) (length / RECORD_SIZE);
return recordCount;
}

The getRecordCount method here includes a throw clause, which ensures that any IOException is thrown up to the calling method.

Our next example shows what happens when we do not catch an exception or throw it.lets see exception handling in java with examples-

public static int getRecordCount()
{
long length = getFileLength(); //this may throw an IOException
int recordCount = (int) (length / RECORD_SIZE);
return recordCount;
}

Since our code fails to catch or throw a checked exception, we’ll receive a compile error:

MyExceptionTest.java.26: unreported exception java.io.IOException;

When we should catch or declared to be thrown?

Early adapter mechanism:

It is a smart thought to fuse special case taking care of into our applications from the get go, before we even begin programming. That is, we should do this at the plan organize, as it gets a lot harder to do it in the wake of executing our applications.

Do not ignore an exception

Notwithstanding whether we are managing a checked or an unchecked exception, absolutely never disregard the exemption.

we generally ignore exception by the following manner:

try {...} catch (SomeException e) {}

The unfilled catch block implies that the exception is just disregarded – it’s not correct. we would prefer not to do this in our projects. At the base, on the off chance that we should incredibly overlook the exemption, put a remark disclosing why we needed to disregard the special case.

we can utilize printStackTrace to yield a basic mistake message to let us know there was an issue.On the off chance that we overlook the exception, as a result of a condition that we have anticipated, it implies that the program will keep running on in spite of the mistake.

Notwithstanding, we’re going to risk a total program disappointment not far off when conditions change.In the event that we spread the exception out, we can guarantee that the program bombs rapidly and catches data that encourages us to fix the mistake.

Exception Handling for every line? Not a good idea

The objective of exception handling is to clear up projects – do whatever it takes not to utilize an try,catch,finally component for each potential exception creating line.

A straightforward procedure is to encase a lot of code inside the try block and determine numerous catch blocks to represent every single imaginable exception. End the entire thing with a finally block on the off chance that we have to discharge any assets held by the program.

Regardless, abstain from setting try,catch,finally every statement that may toss an exception. we will probably utilize exception handling to expel error handling code from the primary program code.

Keep up Failure Atomicity

Continuously endeavor to guarantee that when an item tosses an exception, the object keeps on staying in a well-characterized and usable state.

In a perfect world, even after a strategy flops because of an exception, the object ought to be left in the state it was before the method was conjured, when a method can do this. it’s said to have the property of failure atomicity.

How to keep up Failure Atomicity?

Below are the ways on how we can keep up the Failure Atomiciity.

  • Design Immutable Objects
  • Check Parameters for Validity before the Operation
  • Attempt to Execute the Code before we Modify the item
  • Intercept the Failure
  • Perform Operations on a Temporary Copy of the Object
  • Collect Failure Details
  • Provide accessor methods for all exceptions, especially for checked exceptions.
  • Use Standard Java Exceptions
  • Document All of a Method’s Exceptions

Design Immutable Objects

The simplest method to accomplish failure atomity is by structuring immutable Objects.Despite the fact that when we make an object we can change its contents, every so often, it’s a smart thought to make objects whose contents can not be changed after creation.

Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.

Spread the love
  • 59
  • 85
  • 26
  • 89
  •  
  •  
  •  
  • 14
  •  
  •  
    273
    Shares

LEAVE A REPLY

Please enter your comment!
Please enter your name here