Catching an ArithmeticException but not handling as intended - java

I am kinda new with the whole catching-handling exceptions concept and I was wondering why the throws ArithmeticException doesn't produce an exception error message (in this case/by zero) on exit, but instead during compilation.
Shouldn't it compile normally and then show the error message at the screen? What am I doing wrong?
public class Exception_Tester
{
public static void main(String args[])
{
Exception_Tester et = new Exception_Tester();
int x1;
int x2;
x1 = 5;
x2 = 0;
et.printResults(x1, x2);
}
void printResults(int a, int b) throws ArithmeticException
{
System.out.println("Add: "+(a+b));
System.out.println("Sub: "+(a-b));
System.out.println("Mul: "+(a*b));
System.out.println("Div: "+(a/b));
}
}

I executed your code as it is
public class Exception_Tester
{
public static void main(String args[])
{
Exception_Tester et = new Exception_Tester();
int x1;
int x2;
x1 = 5;
x2 = 0;
et.printResults(x1, x2);
}
void printResults(int a, int b) throws ArithmeticException
{
System.out.println("Add: "+(a+b));
System.out.println("Sub: "+(a-b));
System.out.println("Mul: "+(a*b));
System.out.println("Div: "+(a/b));
}
}
And it compiles fine without any error or exception, and as per your requirement, it is throwing ArithmeticException at run time only when System.out.println("Div: "+(a/b)); statement is encountered.
So I don't See any Problem there!

Checked Exception : these exception will throw error while compilation if you have not handled these exceptions.
Unchecked Exception : you will get error only at RunTime if you have not handled.
ArithmaticException is unchecked exception so you will get exception at runtime.
if you are using try-catch block then you have to use
printStackTrace()
method to print exception stack trace.
as :
try{
System.out.println("Add: "+(a+b));
System.out.println("Sub: "+(a-b));
System.out.println("Mul: "+(a*b));
System.out.println("Div: "+(a/b));
}
catch(ArithmeticException e){
e.printStackTrace();
}

Take a look at the following picture:
As you can see a few of the exception classes are in a bold font to draw our attention to them. Here is the editors explanations about these categories of exceptions
Conditions that can readily occur in a correct program are checked exceptions. Concretely these kind of exceptions are <> by the compiler and he can correctly assess the eventuality of their occurence and declare a compilation error when the circumstances correspond to it. As you can see from the picture, NullPointerException is not directly under this category: these are the exception that directly extends the Exception class.
Severe problems that normally are treated as fatal or situations that probably reflect program bugs are unchecked exceptions.
Fatal situations are represented by the Error class.
Probable bugs are represented by the RuntimeException class. This is the case for exemple with the exceptions that extends the RuntimeException class. NullPointerException is one of them. In most of the cases of this kind of exception the compiler is not able to assess #compile time that they will cause an exception, since there is a strong dependency to the dynamic state of the application
Here is a simple illustration:
I have created two exceptions classes one that extends Exception
public class Exception1 extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
}
and one that extends RuntimeException
public class Exception2 extends RuntimeException {
private static final long serialVersionUID = 4595191052237661216L;
}
Then I have the following NewTester class
public class NewTester {
public static void methodA() throws Exception1 {
throw new Exception1();
}
public static void methodB() throws Exception2 {
throw new Exception2();
}
public static void main(String[] args) {
// methodA();
methodB();
}
}
I have purposefully commented the call to methodA.In this state you don't have any compilation error because the method that is called methodBthrows a RuntimeException which is unchecked. But if you would change this code by uncommenting the call to methodA and commenting the call to methodB you will have a compilation error, because methodA throws a checked exception
I hope this helps

Related

Cannot trigger an exception within an lambda expression

I am somewhat new to Java 8 and am trying to throw a an exception within an lambda expression as following: if subQty is less than min or greater than max, in this case, my unit test calculated min/max to be 182 and 255, and I am submitting a subQty of 10, therefore it should raise an exception and fail this unit test. However, I am keep getting the green light why is that?
public void verifyingIndividualSubmissionValueLimits(String alias, double min, double max)
// ... some code here ...
// Get local stock price
CompletableFuture<Double> localPriceFuture = instrumentRequester.getMidPrice(instId);
// Calculate the min and max quantity
localPriceFuture.thenAcceptBoth(dollarFxRateFuture,
(localPrice, fxRate) -> {
double minLocalValue = min * fxRate;
double maxLocalValue = max * fxRate;
long minQuantity = Math.round(minLocalValue / localPrice);
long maxQuantity = Math.round(maxLocalValue / localPrice);
if (subQty < minQuantity || subQty > maxQuantity) {
log.debug("We should throw an exception because subQty is {}", subQty);
throw new SubmissionValidationException(String.format("Quantity: %s, is not within %s and %s", subQty, minQuantity, maxQuantity));
}
}
);
}
You throws exception in different thread. You are creating a thread that calculate min, max rate and throws an exception but exception occurs in thread so you can not see any exception in main thread (in this case verifyingIndividualSubmissionValueLimits). You can read callback and async threads here https://www.callicoder.com/java-8-completablefuture-tutorial/
You can only throw exception from inside the lambda only if the #FunctionInterface it represent is throwing exception, Otherwise you will have to handle it inside the lambda only, for example this can be achieved creating your own FunctionalInterface -
public class Test {
public void foo(Fun f) throws Exception {
f.apply();
}
#FunctionalInterface
private interface Fun{
void apply() throws Exception;
}
public static void main(String[] args) throws Exception {
Test test = new Test();
test.foo(() -> {
throw new Exception();
});
}
}
In your case you are using CompletableFuture thenAcceptBoth function which use BiConsumer function interface which does not throw any exception, so it's not possible to throw it from there.
#FunctionalInterface
public interface BiConsumer<T, U> {
void accept(T t, U u);
....
}
These are compile time restrictions and valid even if it's not in a separate thread.

Handling exceptions in JAVA

I know that if we have a normal code without try and catch statements,then if an exception occurs,then the default exception handler of JVM handles that exception.
I have a code...
public class St
{
public static void main(String args[])
{
try
{
int y=23/0;
}
catch(Exception e)
{
System.out.println("Division by zero");
}
}
}
As far as I know, in this code exception occurs at line 7,an object of class Exception is thrown and that's why we have taken as argument an object of class Exception in order to catch the exception.Am I right upto now????
But why this code shows a compile time error...
public class St
{
public static void main(String args[])
{
Exception e=new Exception();
try
{
int y=23/0;
}
catch(e)
{
System.out.println("Division by zero");
}
}
}
In this I have created an object reference e of class Exception,and that I have taken as argument in catch.But its not running,giving error at compile time.Can someone explain why???
That's just not how the catch block works. It requires an ExceptionType argument and then a name to reference the exception once it's been caught. It doesn't take an object as an argument, but the name of a class that inherits from 'Throwable'.

How does throws work at Java?

I have been using catch and now I have to use throw.
This is what I 've been given and I can't figure out what's missing so that it will work.
public static void main(String args[]){
Exception_Tester et = new Exception_Tester();
int x1;
int x2;
x1=5;
x2=0;
et.printResults(x1,x2);
}
static void printResults(int a, int b) throws ArithmeticException {
System.out.println("Add: "+(a+b));
System.out.println("Sub: "+(a-b));
System.out.println("Mul: "+(a*b));
System.out.println("Div: "+(a/b));
}
try surrounding the (a/b) in a try statement.
then, in the catch, just throw the exception.
Your printResults method declares that it maight throw an exception of a type ArithmeticException. In order for that to happen something needs to go wrong inside the method, for instance if your b param would be zero an exception would be thrown. If you want to throw exception explicitly you need to use throw statement like this in your method
throw new ArithmeticException();
Before you catch an exception. Your code must throw an exception first. Sometimes there are runtime exceptions, which code itself throws. But sometimes you need a custom Exception to be thrown when some condition gets true. For that you use this throw keyword and throw an exception for your code to Catch it.
Here is a sample
public Object pop() {
Object obj;
if (size == 0) {
throw new EmptyStackException();
}
obj = objectAt(size - 1);
setObjectAt(size - 1, null);
size--;
return obj;
}
It would throw the Exception customly and then you can catch it.
Although if the stack is zero. It might not throw that exception. So you yourself make the code throw that exception for yourself and then handle it somewhere. For that you'll use try { } catch { }.
For more on that: http://docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html
Create a custome exception class and throw the exception from wherever you think it can occur.
public class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
For instance in the division operation in your method. You can use it like..
static void printResults(int a, int b){
if(b == 0 ) {
throw new MyException("Division by Zero");
} else {
System.out.println("Div: "+(a/b));
}
}

Trouble with a thread-safe queue class. Specifically, with exceptions

I am using a thread-safe queue class and have a problem with the insert method I've defined. A Buffer stores an array (elementData) that uses the start/end variables to know where to add/delete stuff from the queue. It's thread-safe, so it uses synchronized methods so I can have multiple threads refer to the same buffer.
public class Buffer<T> {
private T[] elementData;
private int elementCount;
private int start;
private int end;
// Additional fields
// Code to instantiate a Buffer, other methods (e.g. delete)
public synchronized void insert(T t) throws InterruptedException {
while (elementCount == elementData.length) {
wait();
}
end = (end + 1) % elementData.length;
elementData[end] = t;
elementCount++;
notifyAll();
}
public static void main(String[] args) {
Buffer<Integer> b = new Buffer();
b.insert(3);
}
}
Here's my understanding of the situation. When a method such as insert is called, we want to be able to throw an exception that could happen when the main method or some other thread gets called and tries to perform insert while it's suspended. But what I don't understand is why I get this unreported exception. I thought that having a "throws InterruptedException" after the method would be sufficient. Do I need a "try" block? My attempts with try blocks have all failed, so I'm a little stumped as to how to fix this error.
Also, I'm aware that I don't have any actual threads running. I'll do those once I can fix this unreported exception. :) Thanks to anyone who can help.
Buffer.java:56: unreported exception java.lang.InterruptedException; must be caught or declared to be thrown
b.insert(3);
The compile exception is because your insert method could throw an InterruptedException (even if you're not throwing it on purpose), so every method that calls it must use a try/catch block, even if the error never arises:
public static void main(String[] args) {
Buffer<Integer> b = new Buffer();
try {
b.insert(3);
} catch(InterruptedException ie) {
//error handling
e.printStackTrace();
}
}

needn't to catch the exception in the realization of System.out?

I am new to java, and to make clear of "System.out", i read relevant java source code, then find something i cannot understand.
First the source code of "System.out":
public final static PrintStream out = nullPrintStream();
then i went to nullPrintStream
private static PrintStream nullPrintStream() throws NullPointerException {
if (currentTimeMillis() > 0) {
return null;
}
throw new NullPointerException();
}
My question is: the program may throw a NullPointerException in the function nullPrintStream(), and we needn't to catch the exception in public final static PrintStream out = nullPrintStream();? To make clear of it, i wrote some test codes in Eclipse as follows:
package MainPackage;
public class Src {
private static int throwException() throws Exception{
int m = 1;
if(m == 0) {
throw new Exception();
}
return 0;
}
public static final int aTestObject = throwException(); <==Here i got an error
public static void main(String args[]) {
}
}
Just like i think, i got an error Unhandled exception type Exception, but why System.out is OK without doing with the NullPointerException?
Java has a special class of Exceptions called RuntimeExceptions. They all extend the RuntimeException object, which in turn extends the Exception object. The special thing about a RuntimeException (as opposed to a regular exception) is that it does not need to be explicitly thrown. Several different exceptions fit into this category, such as IllegalArgumentException, IllegalStateException etc...
The advantage of using RTE when you are coding is that you do not need to cover your code with a lot of try/catch/throws statements, especially if the exceptions are expected to be extremely rare and unlikely. Additionally, if you have a general mechanism in place for catching RTE, this will also help make sure your app deals with expection conditions cleanly.
That being said, RTEs can be much more difficult to deal with, as it is not obvious from the signature that a particular class or method will throw that type of exception. Consequently, they are not always a good idea for APIs, unless they are well documented.
A NullPointerException is a RuntimeException, and consequently, does not need to be explicitly declared in the method signature.
NullPointerException is a RuntimeException - it doesn't need to be explicitly caught.
if you make your method do this, it won't bomb on compile:
private static int throwException() throws Exception{
int m = 1;
if(m == 0) {
throw new RuntimeException();
}
return 0;
}
if i adhere to throw Exception() in private static int throwException() , how should i modify public static final int aTestObject = throwException();
You can need to intialise the value in a static block and catch the exception there.
public static final int aTestObject;
static {
try {
aTestObject = throwException(); <==Here i got an error
} catch (Exception e) {
throw new AssertionError(e);
}
}

Categories