I have to write logic for detecting what line of code was exception thrown so we can go fix that issue later. The exception object's getStackTrace() gives us a list of stacktrace each with level. I am not interested in getting lowest place where exception was thrown but rather my class method which was responsible in passing parameters.
Here is an example of what i am asking
class Test {
void divide() {
try{
float i = 1/0
}
catch(Exception e){
def v = e.getStackTrace()[0]
println v.getClassName()
}
}
}
This would print class java.math.BigDecimal but i am interested in getting Test class so i can go to it's divide and fix this bug. Now, Test appears in some nth line which i cannot know in run time. One approach would be to iterate stacktrace list and try finding class which is custom developed but how to detect that? Or if there is some library function that already does that it would be great.
Try this:
println e.stackTrace.find {
it.className == 'Test' && it.methodName == 'divide'
}
Or, I guess you want to check all levels of stacktrace, then:
Throwable t = e
StackTraceElement found = null
while (!found && t) {
found = e.stackTrace.find {
it.className == 'Test' && it.methodName == 'divide'
}
t = e.cause
}
println found
Related
In my use case, I am looping across a map and checking whether a particular key is present in a list. If it is present then I have to trow and exception otherwise continue with the execution.
Map<A,B> myMap = new HashMap<A,B>();
//code to populate values in myMap
...
...
List<A> myList = new ArrayList<A>();
//code to populate values in myList
...
...
for(Map.Entry<A,B> eachElementInMap:myMap.entrySet()){
if(myList.contains(eachElementInMap:myMap.getKey())){
//throwing exception
throw new MyCustomizedException("someString");
}
}
//code continues
...
....
In the above example, if there are 3 elements in the map(myMap) in which 1 key is present in the list(myList), I want to throw the exception for one and it should continue executing other lines of code for the rest two. Am I using a wrong design to achieve this? Any help or suggestion is appreciated! Thanks
Typically once you throw an exception, you are saying that the current line of execution should terminate, rather than continue. If you want to keep executing code, then maybe hold off on throwing an exception.
boolean fail = false;
for (Map.Entry<A,B> eachElementInMap:myMap.entrySet()) {
if (myList.contains(eachElementInMap:myMap.getKey())) {
// throw an exception later
fail = true;
}
}
if (fail) {
throw new MyCustomizedException("someString");
}
You can also create an exception object at a different location from where you throw it. This idiom will be useful in cases where the exception message is not just "someString", but needs to be constructed from data obtained from the object being iterated over.
Optional<MyCustomizedException> exception = Optional.empty();
for (Map.Entry<A, B> eachElementInMap:myMap.entrySet()) {
if (myList.contains(eachElementInMap.getKey())) {
// Create an exception object that describes e.g., the missing key(s)
// but do not throw it yet.
if( exception.isPresent() ) {
exception.get().addToDescription( /* Context-sensitive information */ );
}
else {
exception = Optional.of(
new MyCustomizedException( /* Context-sensitive information */));
}
}
}
if( exception.isPresent() ) {
throw exception.get();
}
If the only data stored in the exception is a string, an equivalent effect can be achieved by accumulating problem descriptions in a StringBuilder, but for cases where more interesting data needs to go into the exception object, building as you go might be an option worth considering.
You can split it into two lists,failList and successList. and do it.
This is clearer
failList = myMap.entrySet().stream().filter(p->myList.contains(p.getKey())).collect(Collectors.toList());
successList = myMap.entrySet().stream().filter(p->!myList.contains(p.getKey())).collect(Collectors.toList());
failList.forEach(p -> {
// fail code
});
successList .forEach(p -> {
// success code
});
why not use if...else instead of try catch ? error just means that's a mistake. if you afraid that makes some mistakes what you don't know. you can use throw error.
anyway, it should not be used when the program is running as you wish
I have 2 classes, one that implements a double lookup( int i);
and one where I use that lookup(int i) in solving a question, or in this case printing the lookup values. This case is for an array.
So I read the exception documentation or google/textbook and come with the following code:
public double lookup(int i) throws Exception
{
if( i > numItems)
throw new Exception("out of bounds");
return items[i];
}
and take it over to my class and try to print my set, where set is a name of the
object type I define in the class above.
public void print()
{
for (int i = 0; i < set.size() - 1; i++)
{
System.out.print(set.lookup(i) + ",");
}
System.out.print(set.lookup(set.size()));
}
I'm using two print()'s to avoid the last "," in the print, but am getting an
unhandled exception Exception (my exception's name was Exception)
I think I have to catch my exception in my print() but cannot find the correct formatting online. Do I have to write
catch exception Exception? because that gives me a syntax error saying invalid type on catch.
Sources like
http://docs.oracle.com/javase/tutorial/essential/exceptions/
are of little help to me, I'm can't seem to grasp what the text is telling me. I'm also having trouble finding sources with multiple examples where I can actually understand the coding in the examples.
so could anybody give me a source/example for the above catch phrase and perhaps a decent source of examples for new Java programmers? my book is horrendous and I cannot seem to find an understandable example for the above catch phrase online.
I wouldn't throw Exception ever.
In your case, IndexOutOfBoundException or InvalidArgumentException would eb a better choice. As these are not checked Exceptions, you don't need to catch them.
public double lookup(int i) {
if(i >= numItems) // assuming numItems is not items.length
throw new IndexOutOfBoundException("out of bounds " + i + " >= " + numItems);
return items[i];
}
Note: the check should be >=
Your print() method will now compile unchanged.
What is Exception?
Exceptions are for exceptional conditions. Conditions that normally do not occur. Take an example you went to withdraw money and your account has 100 balance and you asked for 200 then ATM should tell you that you have insufficient balance.
Types of Exceptions
Checked Exception
These are conditions where application wants to recover from it. Like example given above application will give you error and will continue working.
Error
This is an exceptional condition which is external to application. We say OutOfMemoryError when there isn't enough memory available and application can not recover from it.
Runtime Exception /Unchecked Exception
These exceptions are applications exception but in this case application can not recover from it. E.g NullpointerException if value is null and you try do something nasty with it.
so of above three only checked exceptions need to be cached.
How to throw and Catch Checked Exception
Exception or any subclass of Exception is a checked exception. A checked exception can be thrown using throw clause. Once you throw an exception it becomes mandatory for you to include that in method declaration using throws clause.
So whoever want to use this method will now have to handle that exception. Handling exception means invoking alternative flows. Like in our case we displayed text to user "Error Invalid account number."
Calling function can also choose to propagate exceptions by adding throws clause for those exceptions which are thrown by method it is calling.
Generate:
public static double withdraw(int i) throws Exception {
if (i <= 0)// Out of bounds
throw new Exception("Invalid Account Number");
return 0.0;// something;
}
Handle:
try {
withdraw(0);
} catch (Exception e) {
// do something with exception here.
// Log the exception
System.out.println("Error Invalid account number.");
}
Propagate:
public static double callWithdraw(int i) throws Exception {//Propagate exceptions
return withdraw(i);
}
Try this
try
{
print(); //print() needs to throw the same exception
} catch(Exception e)
{
//handle exception
System.err.println(e.getMessage()+"\n\n"+e.printStackTrace());
}
//finally {
// cleanup here if you like
// }
or this
public void print()
{
for (int i = 0; i < set.size() - 1; i++)
{
try
{
System.out.print(set.lookup(i) + ",");
} catch(Exception e)
{
//handle it here
}
}
System.out.print(set.lookup(set.size()));
}
Do note that using "throws" is kind of a easy way out; it's a cheap delegation that sometimes makes coding easier... if you can, you should try to always use try/catch instead of throws.
Just be aware that whenever you use something with "throws" eventually you will have to put that in a try/catch block and deal with it properly.
Generally to denote improper arguments passed into your method, use IllegalArgumentException which is a RuntimeException and should not be caught.
In this specific case you don't have to write any extra code, the ArrayIndexOutOfBoundsException should take care of improper array access.
Thrown to indicate that an array has been accessed with an illegal
index. The index is either negative or greater than or equal to the
size of the array.
I have this line code:
String name = Book.getName();
/*next lines of code*/
Next, variable name processing in other code without any checks.
In some cases, possible situation, when name=null and other code will exit with an error.
It is bad.
Also, I cant access to the other code.
So, what do you think, my next implementation is correct:
try
{
String name = Book.getName();
if(null== name)
throw new NullPointerException("method 'getName' return null");
/*next lines of code*/
}
catch(NullPointerException e)
{
System.out.print("Hey! Where book name? I exit!");
System.exit();
}
I have any other choose in this case?
It is possible to generate any other type of Exception or only NullPointerException?
Thanks.
Edit:
Ok,
String name = Book.getName();
it's imagine code line. In real case, I have more complex code:
List<Book> bookList= new ArrayList<Book>();
String name = null;
Iterator i = BookShop.getBooks.iterator(); //BookShop it is input parameter!
while(i.hasNext())
{
Book book = (Book) i.next;
name = book.getName();
nameList.add(name);
}
This example more full.
So, in this code input parameter BookShop Object.
What problem I can have with this Object?
BookShop can be NULL;
method BookShop.getBooks() can return NULL;
Also, getName() can return NULL too.
So, general problem next: there is no guarantee the correctness of input parameter BookShop!
And I must to consider every possible option (3 NULL)
For me, add General try-catch block and that all.
No?
You can create any exception you like by extending the Exception class, like a NoNameProvidedException for example. There are a lot of example one Google to help you do that.
I guess in your case just checking with an if if the name is null should be sufficient as you just want to do a System.exit().
Your code is a bit iffy, but I assume you're learning. You don't need to throw the NullPointerException explicitly, you can throw whatever Exceptions you like.
But you probably don't really need the Exception catching here, you can just check for the null and handle the situation appropriately if it's true.
Also, please avoid Yoda conditions. Your if statement should read
if name is null
so
if (name == null)
I would probably use IllegalStateException:
String name = Book.getName();
if (name == null) {
throw new IllegalStateException
("Method foo must not be called when the book has no name");
}
It really depends on where the state is coming from though - it's not really clear what's going wrong here.
I certainly wouldn't start catching NullPointerException - exceptions like that (and the illegal state one) shouldn't be explicitly caught. Let them bubble up, and if it's appropriate have some sort of top-level handler.
Exceptions should not be used for normal control flow. Just use the if block:
String name = Book.getName();
if (name == null) {
System.out.print("Hey! Where book name? I exit!");
System.exit();
}
/*next lines of code*/
Using try and catch in this case is unneeded. You can just write like this:
if(Book.getName() != null)
String name = Book.getName();
else
//handle the situation with null
You don't need to throw an Exception in this case - just handle the null value and you are fine.
It's more friendly for Java not to use exceptions, but just check the return value
String name = Book.getName();
if (name == null)
System.out.print("Hey! Where book name? I exit!");
else {
/*next lines of code*/
}
I am using Eclipse Helios IDE for our Web Application development.
Under Problems section in Eclipse, for some of lines the description is displayed as "Dead Code".
Could anybody please tell me what does Dead Code actually mean ?
Please see the screen shot for your reference.
For example this part is shown as dead code under Eclipse
else {
int length;
if (ar != null)
length = Array.getLength(ar);
else
length = 0; // This line is dead code
In Eclipse, "dead code" is code that will never be executed. Usually it's in a conditional branch that logically will never be entered.
A trivial example would be the following:
boolean x = true;
if (x) {
// do something
} else {
// this is dead code!
}
It's not an error, because it's still valid java, but it's a useful warning, especially if the logical conditions are complex, and where it may not be intuitively obvious that the code will never be executed.
In your specific example, Eclipse has calculated that ar will always be non-null, and so the else length = 0 branch will never be executed.
And yes, it's possible that Eclipse is wrong, but it's much more likely that it's not.
Dead code is code that will never be executed, e.g.
boolean b = true
if (!b) {
....
// dead code here
}
Dead code means, that there is no way that this code will be executed.
Sometimes you even can't compile it (like this case:)
private Boolean dead_code()
{
return true;
//Dead code below:
dosomething();
}
But in other cases this is not too obvious, eg this statement:
b=true;
[...]
if (b==false)
{
//Dead code
}
If you have this message, there is some major flaw in your code. You have to find it, otherwise your app won't work as intended.
There are two kinds of diagnostics that Eclipse gives out for marking code that will/may not be executed at runtime.
1) Unreachable code: These are the usual java warnings that follow the unreachability rules of the JLS, and are also given by javac. These are meant to be compile errors. Examples:
int foo() {
return 1;
int i = 1; // Unreachable
}
int foo2() {
while (true);
int i =1; //Unreachable
}
There are other more complicated examples :)
2) Dead code: This is Eclipse's own static analysis warnings, and are mostly tied out of the null analysis i.e.
void foo() {
Object o = null;
if (o == null) {
} else {
// dead code
}
The examples given above should NOT give a dead code warning. i.e.
boolean x = true;
if (x) {
// do something
} else {
// this is dead code!
}
should not give the warning, because JLS forbids the compiler to evaluate the 'value' of variables. All that we can evaluate is the 'nullness'
Hope this helps
You might be having an Null pointer exception in the lines above the "Dead Code" lines.
Make sure you check for "Null Pointer" exception.
It is possible that you have used the variable ar before. Then the compiler knows that the line in the else statement will never be executed. Either there will be a NullPointerException at the place where you used ar or the first part of the if statement will be executed.
let me give some answer for the dead code.
Eg:
public class UnreachableTest{
public static void main(){
try{
// some code
}
catch(Exception exc){
throw new NullPointerException();
System.out.println("Unreachable line"); // compile time error
}
}
}
here the System.out.println("Unreachable line"); is never executed.
Which in turn considered to be a dead code.
Another example may be:
int func(int i, int j)
{
int sum = i + j;
return i + j; // never actually using the sum
}
simple the function returns i + j; never really uses sum.
Sum is considered to be dead code here.
Some other case when this happens.
System.out.println("result :" + result + ":" + result.isEmpty());
if (result == null)
return result;
else if(!result.isEmpty())
str.append(result + " ");
1) Here as you you are printing result and checking isEmpty() eclipse assumes that result is not null so it will not go in if. So return result is dead code.
2)Now let say result is coming null so you will get NullPointerException in result.isEmpty() so again it will not go in if and return result is deadcode
To make this work just comment out System.out.println().
Eclipse gives this warning if the condition check you are giving may never be satisfied. Following are some examples
Object o=null;
if(o!=null) {
//Some code
}
Here Dead code warning will come as Object is already made null
Another example is given below
BSTTest bstTest=null;
bstTest.test=10;
if(bstTest==null) {
//some code
}
Here the code is trying to access a variable of the class. As the variable is already accessed, eclipse will give dead code warning in if(bstTest==null) as bstTest may not be null when the variable is already accessed.
Note: Here bstTest.test will give null pointer exception
Simple Example of Dead Code
public class IfTest {
public static void main(String[] args) {
if (true) {
if(false) {
System.out.println("a"); //Dead code, Never be Execute this if block.
}else {
System.out.println("b");
}
}
}
To simplify the term's Unreachable code and dead code:
Unreachable Code is a code block/statement in Java to which the control never reaches and never gets executed during the lifetime of the program. Following is the example of unreachable code. This generates compiler time error.
public void unreachableCodeExample() {
System.out.println("This will execute");
return;
System.out.println("This will not"); //This is Unreachable code
}
While A Dead code is an unreachable code, but it doesn’t generate compile time error. But if you execute it in eclipse (Or some other IDE) it gives you a warning. See below example,
public void deadCodeExample() {
if (true) {
System.out.println("This will execute");
return;
}
System.out.println("This will not"); //This is dead code
}
Dead code is the section of our code that is never going to execute runtime, its useless
EX:
if(false){ // statements }
For more example u can refer : DeadCode Examples
Try this:
while (true) {
if(false == true) break;
}
S.O.P("I will never reach here!") <-- This code will never be executed.
The code is valid as it conform to the compiler, however in reality the loop will never exit, and in effect S.O.P will never be executed.
I am struggling with this error. I feel its really simple but cannot understand why am getting the error.
I keep getting a NullPointerException when I iterate through values in my linked list.
Code Snippet:
private void updateBuyBook(LimitOrder im) {
LimitOrder lm = null;
Iterator itr = buyBook.entrySet().iterator();
boolean modify = false;
while (itr.hasNext() && !modify) {
Map.Entry pairs = (Map.Entry) itr.next();
if ((((LinkedList<IMessage>) pairs.getValue()).size() > 0)) {
LinkedList<ILimitOrder> orders = (LinkedList<ILimitOrder>) pairs
.getValue();
ListIterator listIterator = orders.listIterator();
while (listIterator.hasNext() && !modify) {
LimitOrder order = (LimitOrder) listIterator.next();
if (order.getOrderID().equalsIgnoreCase(im.getOrderID())) { // error at this line
lm = order;
addToBuyMap(im);
modify = true;
break;
}
}
if (modify = true) {
orders.remove(lm);
break;
}
}
}
}
Error is at this line:
Exception in thread "main" java.lang.NullPointerException
order.getOrderID().equalsIgnoreCase(im.getOrderID()));
Please help. Is my assignment wrong in any way???
Please help!!!
Thanks
Changing your code a bit will make it longer, but much easier to find the error... instead of doing:
if (order.getOrderID().equalsIgnoreCase(im.getOrderID())) {
Change it to:
String orderID = order.getOrderID();
String imOrderID = im.getOrderID();
if(orderID.equals(imOrderID()) {
Then you will know if order or im is null. If neither of those is null then the things that could be null are orderID and imOrderID. It is now a simple matter of finding out which one of those is null.
If it is order or im then the program will crash on the order.getOrderID() or im.getOrderID() lines.
If, instead it is orderID or imOrderID that is null, then it will crash on if(orderID.equals(imOrderID()) {. You can then use System.out.println (or something better, like a debugger) do easily find out what is wrong.
If neither of those should be null then I suggest adding something like:
if(orderID == null) { throw new IllegalStateException("orderID cannot be null"); }
if(imOrderID == null) { throw new IllegalStateException("imOrderID cannot be null"); }
and then track down how it got set to null to begin with.
My guess would be that you're passing in the null, into im. I'll need to see more of the code to be sure.
You never check to see if im is null. I suspect it is.
One first look, where is im instantiated? You can also try to debug in your IDE so as to see whats going on?
Either im is null or order.getOrderID() is returning null.
Doesn't look like im is ever declared / assigned. So
im.getOrderID()
is probably where the null pointer exception is generated.
-- Dan
Edit:
Missed that im is passed in as an argument. So that leaves a few possibilities (in order of likelihood):
im is null (ie. user called function with null parameter)
order.getOrderID() is returning null
order is null (ie. the list has nulls in it)
Edit2:
Your line
if (modify = true)
Is fundamentally wrong and will always evaluate to true (single equal is for assignment, == is for comparison.)
When simply checking if a flag boolean is true or false, it is best to use:
boolean flag = true;
if(flag)
{
// True block
}
else
{
// False block
}
It will be good if you could add a debug point before that line and see which variable is null. looking at the code the answer is 1. order is null 2. order.getOrderID() is null or 3. im is null