Difference Between Java.Lang.Runtimeexception and Java.Lang.Exception

Difference between java.lang.RuntimeException and java.lang.Exception

Generally RuntimeExceptions are exceptions that can be prevented programmatically. E.g NullPointerException, ArrayIndexOutOfBoundException. If you check for null before calling any method, NullPointerException would never occur. Similarly ArrayIndexOutOfBoundException would never occur if you check the index first. RuntimeException are not checked by the compiler, so it is clean code.

EDIT : These days people favor RuntimeException because the clean code it produces. It is totally a personal choice.

What is the difference between Runtime Exception in java and Runtime Error in java?

I Googled for that sentence, and it appears in a sample answer to what appears to be a sample exam question.

(d) Name the type of error (syntax, runtime or logical error) in each case given below:

(i) Math.sqrt (36-45)

(ii) int a;b;c;

This question shows up in a lot of different search results. The funny thing is that while they all agree that (ii) is a syntax error, they disagree on the answer to (i). Some say it is a runtime error, others a logic error1.

The real answer is the correct answer to (i) depends on the context.

  • In some programming languages, this may result in a runtime exception.
  • In other programming languages, it will produce the value NaN.
  • In a programming language that natively supported complex numbers, the answer would be 3i.

To determine whether this is an error at all, you first need to know which programming language we are talking about. It looks like Java2, but there are other possibilities. Then you need to decide whether the program is expecting the predicted exception or NaN or whatever. Consider this Java example:

try {
int a = 1;
int b = 0;
int c = a / b; // This will throw an exception in Java.
} catch (AritheticException ex) {
System.out.println("Success!");
}

The division by zero in the above is (arguably) not an error at all. We were expecting it, and we handled it. An exception in Java is a way to signal an exceptional event. It is not necessarily a runtime error.

Back to the original sqrt(-9) example, in that case Java does not throw an exception. Instead it returns NaN which is a legitimate IEE 768 floating point value. Is that an error? Well it actually depends on that the program does with that value.

In short: the question is ambiguous, and doesn't have a single correct answer.

It is a shame that school curricula are perpetuating this kind of thinking. One would hope that both "runtime error" and "logical error" would be accepted as correct answers if this particular question came up in a real exam. But ...


1 - One answer even said it was a syntax error because there is no semicolon.

2 - Even assuming this is Java, Math.sqrt is not necessarily the java.lang.Math.sqrt(double) method. It could be a different Math class, or if the programmer is ignoring style, Math could even be a variable name.

Extending Exception/RunTimeException in java?

RuntimeException are unchecked while Exception are checked (calling
code must handle them).

The custom exception should extends RuntimeException if you want to make it unchecked else extend it with Exception.

With unchecked exceptions calling code method is not required to declare in its throws clause any subclasses of RuntimeException that might be thrown during the execution of the method but not caught.

As the calling method may not handle `RuntimeException``, one needs to be careful while throwing RuntimeException.

Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small.

Runtime exceptions can occur anywhere in a program, and in a typical one they can be very numerous. Having to add runtime exceptions in every method declaration would reduce a program's clarity. Thus, the compiler does not require that you catch or specify runtime exceptions (although you can).

Source/Further Reading: Unchecked Exceptions - The Controversy

Unchecked and runtime exceptions in java

All runtime exceptions (e.g. NullPointerException) are unchecked exceptions.

Since errors (e.g. StackOverflowError) are also unchecked exceptions, not all unchecked exceptions are runtime exceptions.

The Java Language Specifications define an unchecked exception: "The unchecked exception classes are the run-time exception classes and the error classes."

Fatal error VS Exception

Read the Java tutorial on Exceptions.

For short explanation you may use this small guide. See the class diagram with the Java Exception hierarchy (red) and a few examples (blue) in each category.

Sample Image

Throwable: the common ancestor of anything which can be thrown (and caught) using the Java exception mechanism.

Error: you may think about Errors as about what you call "fatal exception". It usually does not make sense to even try any recovery of the application. OutOfMemoryError or StackOverflowError are such fatal errors that you can hardly do anything within the application.

Do not catch Errors, let the program crash and solve the issue outside.

RuntimeException: should be used for mostly programmer's errors (see the following example), such as not-handled null pointer de-reference, not fulfilling method contracts etc.

Although they are techniques where all the exceptions are wrapped into RuntimeExceptions and handled outside of the business code (typically with AOP), normally an occurence of a RuntimeException means that you should let the program crash and fix its source code.

/**
* Does something with s.
* @param s The input string
*/
public void badlyDesignedMethod(String s) {
// Here the programmer omitted to check s against null
int i = s.length();
...
}

/**
* Does something with s.
* @param s The input string; must not be null
*/
public void betterDesignedMethod(String s) {
if (s == null) {
throw new IllegalArgumentException("The parameter s must not be null!");
}
int i = s.length();
...
}

public void caller() {
badlyDesignedMethod(null); // will throw NullPointerException
// It is the fault of the programmer of badlyDesignedMethod()
// as they have not specified that the parameter must not be null.

betterDesignedMethod(null); // will throw IllegalArgumentException
// Now it is the fault of the programmer of caller()
// as they violated the contract of betterDesignedMethod()
// which DOES tell them that the parameter must not be null
}

Both the Errors and RuntimeExceptions are unchecked, which means that a method does not have to declare that it throws them and the callers do not have to catch them, i.e. do not have surround the call with try-catch block.

Other exceptions (inherited from Exception and not from RuntimeException): exceptions which should be declared (throws...) and caught (try-catch), which are mostly intended carrying useful information from a method to its caller: database is not available, file cannot be opened etc.

These are exception which are meant to be handled by your code. They are "expected exceptions", comparing to the run-time exceptions which are "unexpected exceptions".

public void doSomethingWithFile(String fileName) throws IOException {
if (/* file is not accessible */) {
throw new IOException("File " + fileName + " is not accessible!");
}
...
}
public void caller() {
try {
doSomethingWithFile("/home/honza/file.txt");
}
catch (IOException e) {
// handle the fact that the file is not accessible
return;
}
...
}


Related Topics



Leave a reply



Submit