Exception in java
When do you use exception in Java?
Some cases where Exceptions can be preferred over other types of Error handling, without causing a bigger debate about it.
The question does not specify any references. It is not clear if the post ask for what an exeception is meant to be used for or where Exceptions should be used over traditional error handling. I will assume the readers have a basic understanding of exceptions and compare error handling with exception due to traditional error handling.
There are in general 3 major ways of handling errors (supported by Java, which means goto is not discussed).
1) Throw the exeception, which basically means that error handling is either done with try-catch and finally or forward the current exception.
2) Handling Errors with return codes and if statements
3) This is basically a variant of (2). Sometimes different comparison functions or “is-functions” (“isAvailable()”, “exist()”, “equals()”…) can be used. (This also includes checking for null, but it is not explicitly mentioned since null is not formally an error and may not always be seen as one. The general view of returning null from a function is that it is a code small.)
There is a lot of material discussing this, but I will give you a short summary of some generally accepted facts.
When to use Traditional error handling(2):
is in general not encoraged anymore. The error code system was useful before Exceptions existed, but handling errors like this is cumbersome. Assume for example that you want to return a variable from a function. To also return an error code if something goes wrong, you need to wrap the error and return value in a class and return an instance of this class.
This can be very complicated. The other way is to pass the reference to the class as a parameter. This is not that suitable either when it comes to polymorphism. The reason for this is that if a function is supposed to “return” a new object, the object have to be created beforehand and this requires the calling function to know the concrete type before calling the function.
What is exception handling in Java?
- Let’s say you are an airlines company. Now there might be some rules and regulations for all airlines. For example, having a pilot and staff on plane is pretty mandatory. If you violate this rule, you don’t get to fly. This would be a compile time error. The compiler refuses to compile the code itself when you violate code rules.
- Airlines must have safety measurements in their planes in case of any emergency. The speech given by the air hostess about safety is the airlines saying “ hey, things could go wrong”. That’s declaring an Exception. You do this by using “throws” in the declaration of a risky method.
- All airline planes have life jackets under each seat to protect passengers if the plane crashes into sea. That life jacket is an exception handling. You achieve it by by wrapping the risky code in try and catch blocks.
- Now what if the plane crashes above land and not on sea? There are no parachutes. You are ducking the exception. When nobody handles an exception, not even the main(), then the JVM just terminates the program with the exception.(People die in plane crash).
- Also, in general plane crashes because of engine failure or pilot’s mistake. The pilot may try to land the plane safely. These are runtime exceptions. You can try to handle them. But the compiler doesn’t care if you don’t declare or handle runtime exceptions. All the other exceptions are checked exceptions, which should be declared, otherwise compiler throws a compile time error.
- Let’s say two planes were going from A to B. Plane 1 crashed into sea(exception), but passengers survived using life jackets(catch). Ultimately, you need to take both plane 1 and 2 passengers to their destination B. This is where finally comes into picture. You put the code that should run no matter what-exception or not, in to a finally block.
Enough with the lame example, in short Exception is an object which you throw in case of an exception. You can throw any subclass of an Exception. Exception extends Throwable.
RuntimeException(unchecked) and other checked exceptions extend Exception. You can define your own exceptions by extending either Exception or RuntimeException(to create an unchecked exception). You declare that a method is risky by throws clause. You throw an exception object using throw.
e.g: public void read() throws IOException{
//Your code
throw new IOException();
}
To catch an exception, you write a try-catch block. Finally block always executes.
try{
//Exception code
}catch(IOException e){
e.printStackTrace();
}
finally{
//close all resources
}
A try block should at least have a catch or a finally block. There can be multiple catch blocks to handle multiple exceptions. Always remember the order of exceptions in catch blocks should be from subclass to superclass. That is if you Exception should be in last catch block, other subclasses should be in first catch blocks.
I hope this helps.
Head First Java has a good explanation of java basics. You can try that to get a better understanding of java concepts.
What is Java Nullpoint exception?
NullPointerException is an Exception which Java can throw at runtime. Its name is confusing because it is not possible to create pointers explicitly in Java! But it has been around since the very start of the Java language, and wisely, the Java designers never change anything that would break existing code, so the confusing name remains.
When you create a variable in Java that can hold any kind of object, that variable is a reference. You can think of it like a pointer to a memory location, except that you can’t access the real pointer, only a reference to it.
In Java, all object references can hold either a pointer to one instance of an object, or the special value null, which means no object. That’s part of the definition of the Java language.
If you try to access an object in a variable at runtime, and at that time it is a reference to null, then Java will throw a NullPointerException to tell you that the object you were expecting has not been assigned to your variable.
It’s very common to see checks for null in Java code, to avoid this exception being thrown. Some other languages have special types of expression that only proceed if none of the object references are null, but Java doesn’t, which I think is a pity.