Try catch exceptional handling [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have been trying using the Arraylist, but that dint seem to work
I need one simple example for index out of bound exception handling using the try catch blocks in java
This is my code, how do I integrate with try catch blocks to handle the exception?
import java.util.ArrayList;
public class NewClass2 {
public static void main(String[] args) {
ArrayList<String> lis = new ArrayList<>();
lis.add("My");
lis.add("Name");
// in the next line, an IndexOutOfBoundsException occurs
System.out.println(lis.get(2));
}
}
Can I also get an example for Illegal Argument exception using the try catch

Don't try to use try/catch blocks to catch the exception. You can check if the index you are trying to pass is negative, or greater than or equal to the size, and avoid the exception ever being thrown in the first place.
As described in the Javadoc of ArrayList.get(int):
[Throws] IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size())
So, just check this in your code:
if (i >= 0 && i < lis.size()) {
// Do something for an index in bounds.
} else {
// Do something for an index out of bounds.
}
Only use exception handling for cases which you cannot avoid by checking in advance. This is covered in detail in Effective Java; in the 2nd Ed this is Item 57: "Use exceptions only for exceptional conditions".

Here is a basic example:
int[] num = {1, 3, 4, 5};
try {
System.out.println(num[30]);
}
catch(ArrayIndexOutOfBoundsException e) {
e.printStackTrace(System.out);
}
And for an ArrayList:
try {
ArrayList<String> lis = new ArrayList<String>();
lis.add("My");
lis.add("Name"); System.out.println(lis.get(2));
}
catch(IndexOutOfBoundsException e) {
e.printStackTrace(System.out);
}

As many people already stated, you are trying to access the third element (index = 2, indexes start at 0) of a data structure that has only 2 elements.
However, you could apply try-catch for this like the following, for example:
public static void main(String[] args) {
ArrayList<String> lis = new ArrayList<>();
lis.add("My");
lis.add("Name");
// now you just try the access
try {
System.out.println(lis.get(2));
// and especially handle the IndexOutOfBoundsException
} catch (IndexOutOfBoundsException ex) {
System.err.println("You are trying to access an index that is not available (out of bounds)!");
ex.printStackTrace();
}
}

Related

how to handle null pointer exception while creating on demand singleton object [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Hi there ,
I am facing an issue with creating only three singleton object.
if the number of object increase after 3. Program throwing NullPointerException.
so I am trying to put the code inside try and catch but getting error mentioned below
Syntax error on tokens, ConstructorHeaderName expected instead
try {
public static Singleton getInstance() {
if (Singleton.counter < 3) {
System.out.println("counter no"+ Singleton.counter);
single_instance = new Singleton();
return single_instance;
} else
return null;
}
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
Your code has a syntax error. try, catch should be inside the method body like this:
public static Singleton getInstance() {
try {
if (Singleton.counter < 3) {
System.out.println("counter no"+ Singleton.counter);
single_instance = new Singleton();
return single_instance;
} else
return null;
}
catch (NullPointerException e) {
System.out.println(e.getMessage());
}
}

Is it possible to make a catch block that waits until the whole try block is executed?

What I'm doing
I'm trying to make a cleaner version of nested try catch blocks and I'm solving a very basic exception problem while doing so. I'm making a calculator that will do great things. Before then however, it must take in user inputs as strings and convert them to either floats or integers. I'm doing this by simply calling the in built parseInt and parseFloat functions of java. Right now I'm using a nested try catch block to do this:
String stringToParse = "1.0"
try{Integer.parseInt(stringToParse);}
catch(NumberFormatException n){
try{Float.parseFloat(stringToParse);}
catch(NumberFormatException n){
System.out.println(n)
}
}
Why is that a problem?
This is messy to me and I'd rather have a try block that collects the errors but doesn't immediately go to the catch block, rather it executes the entire try and catches any errors after the try has been executed. I've made a runnable example of this myself that shows what I desire:
String num = "1.0";
int i = 0;
ArrayList<Object> listofResults = new ArrayList<>();
ArrayList<Integer> listOfErrorIndices = new ArrayList<>();
try {
listofResults.add(Integer.parseInt(num));
i++;
listofResults.add(Float.parseFloat(num));
i++;
listofResults.add(Integer.parseInt(num));
} catch (NumberFormatException n) {
listOfErrorIndices.add(i);
}
for (Integer element:listOfErrorIndices) {
System.out.println(element);
//this currently prints out 0 and I want it to print out both 0 and
//2 so that it catches both errors.
}
My idea of how to solve the problem/What I've tried otherwise
My plan is to gather a list of all the NumberFormatException indices (i) thrown in the try. Each time I try to parse the string, an element is added to the resultsList. My goal is to then use this theoretical try catch block to obtain the indices of all the exceptions and then remove them from the resultsList if they threw an error. TLDR; Right now the above code prints out 0 and I want it to print out 0 and 2. Basically, Instead of having nested try catch blocks I use list comprehension and Exception handling indicies with i to remove the error results and only keep the good ones. I don't know if this is possible hence this question. I've looked at the "better ways to implement nested try catch blocks" question however it wasn't useful to me because It provided a solution in delphi and I didn't understand exactly how it worked or if it even worked the way I want mine to work. I at first thought the finally block might be what I needed but that only runs after the catch is executed or if there is no exception, after the try. I need something that postpones the catch block untill the try is complete and I can't think of/find anything that does that.
What are you, crazy?
right now you may be asking, what the hell is the point of this? Well imagine if you had the above problem but instead of two ways to parse the string you had 10 or 100. Pretty quickly, exception handling that with nested try catch blocks would be nigh impossible. I've seen solutions where the catch block calls a custom exception method that then at least takes care of the bad formatting. It looked like this:
try{
//bad code
}
catch{
trysomethingelse();
}
trysomethingelse(){
//equally bad code
catch{
//ya done screwed up son
}
}
However I'm not satisfied because it means that you need a million different method names just to potentially handle one error. Imagine the error would always be the same you just need to try 100 different string parsing methods. Its always going to be a numberformatException if you're trying to convert a string to a number so why have a million catch blocks just for the same error? I want to try to do this with one theoretical catch block that specifies one error that happens many times over in the try block.
You build a list/array of parsers, then iterate that list, catching exception for each.
With Java 8 method references, this is real easy. First, define a Parser functional interface that allows exceptions to be thrown:
#FunctionalInterface
public interface Parser {
Object parse(String text) throws Exception;
}
Next, build your array of parsers to try:
Parser[] parsers = {
Integer::valueOf,
Double::valueOf,
BigInteger::new,
BigDecimal::new
};
Finally, try them one at a time:
String text = "45.8";
Object[] results = new Object[parsers.length];
for (int i = 0; i < parsers.length; i++) {
try {
results[i] = parsers[i].parse(text);
} catch (Exception e) {
results[i] = e;
}
}
Now you can go through the results:
for (Object result : results) {
if (result instanceof Exception)
System.out.println("Error: " + result);
else
System.out.println("Parsed as " + result.getClass().getSimpleName() + ": " + result);
}
Output
Error: java.lang.NumberFormatException: For input string: "45.8"
Parsed as Double: 45.8
Error: java.lang.NumberFormatException: For input string: "45.8"
Parsed as BigDecimal: 45.8
Or put the parsed objects and the exceptions into two different lists. Up to you.
You can do something like this:
interface Parser {
Number parse(String);
}
class IntegerParser implements Parser {
#Override
public Number parse(String) {
// implementation here
}
}
class FloatParser implements Parser {
}
List<Parser> parsers = asList(new FloatParser(), new IntegerParser(), ...);
Number result = null;
List<NumberFormatException> exceptions = new ArrayList<>();
for (Parser parser : parsers) {
try {
result = parser.parse(stringToParse);
break;
} catch (NumberFormatException e) {
exceptions.add(e);
}
}
if (result != null) {
// parsed ok with some parser
// probably discard exceptions
} else {
// show exceptions from the list
}
Try this:
public static void test() {
final String num = "1.0";
final ArrayList<Object> listofResults = new ArrayList<>();
final java.util.function.Function<String, ?>[] parseMethods = new java.util.function.Function[3];
parseMethods[0] = Integer::parseInt;
parseMethods[1] = Float::parseFloat;
parseMethods[2] = Integer::parseInt;
int[] badIndeces = IntStream.range(0, parseMethods.length).map(i -> {
try {
listofResults.add(parseMethods[i].apply(num));
return -i-1;
} catch (NumberFormatException exc) {
return i;
}
}).filter(i -> i >= 0).toArray();
for (int element : badIndeces) {
System.out.println(element);
}
}

Refactoring if-else if chain in Java 8 style [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a method with the following if-else-if chain:
if(downstreamActual.getNumber() <= downstreamRecommended.getNumber()){
downstreamActual.setInvalid();
showErrorWindow();
throw new NumberFormatException();
}else if(upstreamActual.getNumber() <= upstreamRecommended.getNumber()){
upstreamActual.setInvalid();
showErrorWindow();
throw new NumberFormatException();
}else if(biUpstreamActual.getNumber() <= biUpstreamRecommended.getNumber()){
biUpstreamActual.setInvalid();
showErrorWindow();
throw new NumberFormatException();
}else if(biDownstreamActual.getNumber() <= biDownstreamRecommended.getNumber()){
biDownstreamActual.setInvalid();
showErrorWindow();
throw new NumberFormatException();
}
Every step we do the same work (call the same method for first object that uses in boolean expression, call showErrorWindow() and throw an Exception)
What are some good techniques especially using Java 8 to make this code more manageable?
Based on your comment, I don't think you need Java 8 constructs.
Just use a method :
public void validate (NumberTextBox actual, NumberTextBox recommended)
{
if(actual.getNumber() <= recommended.getNumber()) {
actual.setInvalid();
showErrorWindow();
throw new NumberFormatException();
}
}
Then call it 4 times :
validate (downstreamActual,downstreamRecommended);
validate (upstreamActual,upstreamRecommended);
...
Since the first one that fails would throw an exception, thus preventing the rest of them from being tested, you don't need the if else-if structure.
I cannot see the java 8 involvement here, but one thing you could do is create a method for that piece of if-else chain in the following manner:
public void handleStreams() throws NumberFormatException {
if(downstreamActual.getNumber() <= downstreamRecommended.getNumber()) {
setInvalid(downstreamActual);
} else if(upstreamActual.getNumber() <= upstreamRecommended.getNumber()) {
setInvalid(upstreamActual);
} else if(biUpstreamActual.getNumber() <= biUpstreamRecommended.getNumber()) {
setInvalid(biUpstreamActual);
} else if(biDownstreamActual.getNumber() <= biDownstreamRecommended.getNumber()) {
setInvalid(biDownstreamActual);
} else {
return;
}
showErrorWindow();
throw new NumberFormatException();
}
public void setInvalid(MyObject stream) {
stream.setInvalid();
}
If those streams have a common super class then you can implement this directly in them. In other words if
public class DownstreamActual extends CustomStream {
then you can add recommendation as a variable to the CustomStream class
public int recommendedValue;
and set it when you create the instance.. Then you can create a method which will check the values
public void checkRecommendedValue() {
if(this.getNumber() <= this.recommendedValue){
this.setInvalid();
showErrorWindow();
throw new NumberFormatException();
}
}
One thing you can do with java 8 is avoid making a separate method (if that calls to you) and create one right inside your method using the new syntax:
BiConsumer<Thing, Thing> check = (actual, recommended) -> {
if (actual.getNumber() <= recommended.getNumber()) {
actual.setInvalid();
showErrorWindow();
throw new NumberFormatException();
}
};
check.accept(downstreamActual, downstreamRecommended);
check.accept(upstreamActual, upstreamRecommended);
check.accept(biUpstreamActual, biUpstreamRecommended);
check.accept(biDownstreamActual, biDownstreamRecommended);

NullPointerException with an ArrayList inside of a HashMap [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am attempting to use an arraylist inside of a hashmap to create and iterate counters for different characters fed to the processLine method. I think I have declared all of the variables and the catch statements should handle the cases in which there isn't an entry in the hashmap, but I am still getting a NullPointerException on the curCounts.set(i, 1); line in the second catch statement. I've probably made some dumb mistake, but I can't figure out what it is.
HashMap<Character, ArrayList<Integer>> charCounts;
public DigitCount() { charCounts = new HashMap<>(); }
public void processLine (String curLine) {
int length = curLine.length();
char curChar;
ArrayList<Integer> curCounts;
Integer curCount;
for(int i = 0; i < length; i++){
curChar = curLine.charAt(i);
try {
curCounts = charCounts.get(i);
} catch (NullPointerException ex) {
curCounts = new ArrayList<>();
}
try {
curCount = curCounts.get(i);
curCount++;
curCounts.set(i, curCount);
} catch (NullPointerException ex) {
curCounts.set(i, 1);
}
charCounts.put(curChar, curCounts);
}
linesProcessed++;
System.out.println("---------------------------" + linesProcessed);
}
Edit: Yes, I did call DigitCount.
public static void main(String args[]) throws Exception
{
//creates an instance of the digitCount object and starts the run method
DigitCount counter = new DigitCount();
counter.run(args[0]);
}
if charConts doesn't contain i (as in charCounts.get(i)), then it won't throw a NullPointerException, it will return null. Therefore you should be using an if and not a trycatch as in:
curCounts = charCounts.get(i);
if(curCounts==null)
curCounts = new ArrayList<>();
Edit: Alternatively if you are using java 8 you can do
curCounts = charCounts.getOrDefault(i,new ArrayList<Integer>());
and it will automatically default to creating a new ArrayList if it doesn't contain one

Catching nullpointerexception in Java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I tried using try-catch block to catch NullPointerException but still the following program is giving errors. Am I doing something wrong or is there any other way to catch NullPointerException in the following program. Any help is highly appreciated.
public class Circular_or_not
{
/**
* #param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
try
{
LinkedListNode[] nodes = new LinkedListNode[10];
for (int i = 0; i < 10; i++)
{
nodes[i] = new LinkedListNode(i, null, i > 0 ? nodes[i - 1] : null);
}
// Create loop;
// nodes[9].next = nodes[3];
Boolean abc= Check_Circular(nodes[0]);
System.out.print(abc);
}
catch(NullPointerException e)
{
System.out.print("NullPointerException caught");
}
}
public static boolean Check_Circular(LinkedListNode head)
{
LinkedListNode n1 = head;
LinkedListNode n2 = head;
// Find meeting point
while (n2.next != null)
{
n1 = n1.next;
n2 = n2.next.next;
if (n1 == n2)
{
return true;
}
}
return false;
}
}
NullPointerException is a run-time exception which is not recommended to catch it, but instead avoid it:
if(someVariable != null) someVariable.doSomething();
else
{
// do something else
}
As stated already within another answer it is not recommended to catch a NullPointerException. However you definitely could catch it, like the following example shows.
public class Testclass{
public static void main(String[] args) {
try {
doSomething();
} catch (NullPointerException e) {
System.out.print("Caught the NullPointerException");
}
}
public static void doSomething() {
String nullString = null;
nullString.endsWith("test");
}
}
Although a NPE can be caught you definitely shouldn't do that but fix the initial issue, which is the Check_Circular method.
The problem with your code is in your loop in Check_Circular. You are advancing through the list using n1 by going one node at a time. By reassigning n2 to n2.next.next you are advancing through it two at a time.
When you do that, n2.next.next may be null, so n2 will be null after the assignment. When the loop repeats and it checks if n2.next is not null, it throws the NPE because it can't get to next since n2 is already null.
You want to do something like what Alex posted instead.
I think your problem is inside CheckCircular, in the while condition:
Assume you have 2 nodes, first N1 and N2 point to the same node, then N1 points to the second node (last) and N2 points to null (because it's N2.next.next). In the next loop, you try to call the 'next' method on N2, but N2 is null. There you have it, NullPointerException
You should be catching NullPointerException with the code above, but that doesn't change the fact that your Check_Circular is wrong. If you fix Check_Circular, your code won't throw NullPointerException in the first place, and work as intended.
Try:
public static boolean Check_Circular(LinkedListNode head)
{
LinkedListNode curNode = head;
do
{
curNode = curNode.next;
if(curNode == head)
return true;
}
while(curNode != null);
return false;
}

Categories

Resources