Question #31505

There are instances where the utilization of checked exceptions are more appropriate than unchecked exceptions in exception handling. Provide an example of each exception not mentioned in the article. Explain why each type of exception is more appropriate.
1

Expert's answer

2013-06-04T12:05:38-0400

An exception is a problem that arises during the execution of a program. An exception can occur for the following reasons:

1. A user has entered invalid data.

2. A file that needs to be opened cannot be found.

3. A network connection has been lost in the middle of communications, or the JVM has run out of memory.

There are three categories of exceptions:

1. Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.

2. Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compilation.

3. Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.

A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following:


try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
}


For example:

The following is an array is declared with 2 elements. Then the code tries to access the 3rd element of the array which throws an exception.


// File Name : ExcepTest.java
import java.io.*;
public class ExcepTest{
public static void main(String args[]){
try{
int a[] = new int[2];
System.out.println("Access element three : " + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown : " + e);
}
System.out.println("Out of the block");
}
}


This would produce following result:


Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!
LATEST TUTORIALS
APPROVED BY CLIENTS