# Using the try{} catch() {}

**URL:** https://discourse.processing.org/t/using-the-try-catch/26108
**Category:** Beginners
**Created:** [December 10, 2020, 9:39am UTC](https://discourse.processing.org/t/using-the-try-catch/26108 "2020-12-10T09:39:10Z")
**Posts on this page:** 11
**Page:** 1

<div class="post-metadata">

### Author: ![CodeMasterX](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/codemasterx/32/2942_2.png) [@CodeMasterX](https://discourse.processing.org/u/CodeMasterX)
#### Post date: [December 10, 2020, 9:39am UTC](https://discourse.processing.org/t/using-the-try-catch/26108/1 "2020-12-10T09:39:10Z")

</div>

Hi! I recently saw a function

```auto
try{

} catch() {

}

```

I am curently working on a “game of life” project. I use the `int[][] grid = new int[w][h]`.  
It is annoying if I have to use

> if(i \> 0) { grid[i-1][j] }

everytime I check (8 times)

how would i be able to use it?

```auto
int w = 20, h = 10;
float scl;
boolean grid[][] = new boolean[w][h];
boolean survive[][] = new boolean[w][h];

void setup() {
  size(800,400);
  scl = width/w;
  stroke(255);
}

void draw() {
  background(0);
  for(int i = 0; i < w; i++) { 
    for(int j = 0; j < h; j++) {
      fill( ((grid[i][j])? 255 : 0));
      rect(i*scl,j*scl,scl,scl);
    }
  }
}

void mousePressed() {
  int x = floor(map(mouseX,0,width,0,w)), y = floor(map(mouseY,0,height,0,h));
  grid[x][y] = !grid[x][y];
}

void check() {
  for(int i = 0; i < w; i++) {
    for(int j = 0; j < h; j++) {
      int sum = 0;
      
      for(int a = -1; a < 3; a++) {
        for(int b = -1; b < 3; b++) {
          
          try {
            
          } catch {
            
          }
          
          
        }
      }
      
      if(sum == 3) {
        survive[i][j] = true;
      } else {
        survive[i][j] = false;
      }
    }
  }
}

```

---

<div class="post-metadata">

### Author: ![Chrisir](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/chrisir/32/45_2.png) [@Chrisir](https://discourse.processing.org/u/Chrisir)
#### Post date: [December 10, 2020, 10:30am UTC](https://discourse.processing.org/t/using-the-try-catch/26108/2 "2020-12-10T10:30:22Z")

</div>

instead of using try catch here, you could use a function checkIndex(i,j) which returns true or false

```auto

boolean checkIndex(i,j) {
    if(i>0&&i<5&&
    j>0&&j<5) 
    return true;
    else 
    return false; 
}

```

---

<div class="post-metadata">

### Author: ![CodeMasterX](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/codemasterx/32/2942_2.png) [@CodeMasterX](https://discourse.processing.org/u/CodeMasterX)
#### Post date: [December 10, 2020, 6:13pm UTC](https://discourse.processing.org/t/using-the-try-catch/26108/3 "2020-12-10T18:13:05Z")

</div>

I used this method in my previous GOL project. After I couldn’t find a way to use the try command I just reused the previous code.

I am not only learning the try command for this project, just like how I used arraylists for some projects where that wasn’t needed.

---

<div class="post-metadata">

### Author: ![CodeMasterX](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/codemasterx/32/2942_2.png) [@CodeMasterX](https://discourse.processing.org/u/CodeMasterX)
#### Post date: [December 10, 2020, 8:00pm UTC](https://discourse.processing.org/t/using-the-try-catch/26108/4 "2020-12-10T20:00:31Z")

</div>

so how to use the try{}?

---

<div class="post-metadata">

### Author: ![noel](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/noel/32/213_2.png) [@noel](https://discourse.processing.org/u/noel)
#### Post date: [December 10, 2020, 8:28pm UTC](https://discourse.processing.org/t/using-the-try-catch/26108/5 "2020-12-10T20:28:28Z")

</div>

> **[Java - Exceptions - Tutorialspoint](https://www.tutorialspoint.com/java/java_exceptions.htm)**

---

<div class="post-metadata">

### Author: ![quark](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/quark/32/26_2.png) [@quark](https://discourse.processing.org/u/quark)
#### Post date: [December 11, 2020, 9:08am UTC](https://discourse.processing.org/t/using-the-try-catch/26108/6 "2020-12-11T09:08:31Z")

</div>

Although understanding exception handling and being able to use the `try...catch` construct is good to know, it is more important to know when to use it.

The `try...catch` construct should be used to catch exceptional errors and iterating over an array should not cause exception because we always know the array or list size.

So by all means learn it, but don’t use it in a GoL project.

Game of Life is a fun interesting project which I first implemented several decades ago when I was fairly new to programming. It wasn’t very efficient but as my programming skills improved so has my algorithm to the point I have _ **no need to perform any** _ arrays bounds checking. It uses just two 2D arrays and a list. If you are familiar with bit operations it can be done with just one 2D array and a list. (you can see the algorithm in action here on my [website](http://www.lagers.org.uk/))

I know this discussion is about `try...catch` so I won’t explain the algorithm here unless you want me to, 😃

---

<div class="post-metadata">

### Author: ![Chrisir](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/chrisir/32/45_2.png) [@Chrisir](https://discourse.processing.org/u/Chrisir)
#### Post date: [December 15, 2020, 2:44pm UTC](https://discourse.processing.org/t/using-the-try-catch/26108/7 "2020-12-15T14:44:58Z")

</div>

This gives an error:

```auto
float a = 6 / 0;

println(a);

```

* * *

Here is with try catch

```auto

float a = 0;

try {
  a = 6 / 0;
} 
catch( Exception e ) {
  println("catching...."); 
  println ("e says: "+e);
  e.printStackTrace();
}

println(a);

```

Chrisir

---

<div class="post-metadata">

### Author: ![neilcsmith](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/neilcsmith/32/144_2.png) [@neilcsmith](https://discourse.processing.org/u/neilcsmith)
#### Post date: [December 15, 2020, 3:09pm UTC](https://discourse.processing.org/t/using-the-try-catch/26108/8 "2020-12-15T15:09:14Z")

</div>

> [@quark](#):
>
> The `try...catch` construct should be used to catch exceptional errors

This cannot be overstated! Never\* use exceptions and try/catch for program logic. Using `try` when the exception doesn’t happen is very efficient - triggering the `catch`, and particularly the actual creation of the exception, is really inefficient.

- OK, as with everything, almost never - there are cases - this definitely isn’t one of them!

---

<div class="post-metadata">

### Author: ![Chrisir](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/chrisir/32/45_2.png) [@Chrisir](https://discourse.processing.org/u/Chrisir)
#### Post date: [December 15, 2020, 7:07pm UTC](https://discourse.processing.org/t/using-the-try-catch/26108/9 "2020-12-15T19:07:08Z")

</div>

Especially when your program is still in the making and not yet finished, try-catch can obscure the true cause of an error. Very dangerous.

As far as I know it’s there to check when something breaks during you run the Sketch, e.g. a file you load is not there or an Internet resource. It’s a trick for the unforeseeable, not for the foreseeable.

---

<div class="post-metadata">

### Author: ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)
#### Post date: [December 15, 2020, 7:18pm UTC](https://discourse.processing.org/t/using-the-try-catch/26108/10 "2020-12-15T19:18:36Z")

</div>

> [@neilcsmith](#):
>
> OK, as with everything, almost never - there are cases -

[NumberFormatException](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/NumberFormatException.html) is a very notable case where its `catch () {}` block works as an `if () {}` replacement: 😉

> [@Help determining data type](https://discourse.processing.org/t/help-determining-data-type/26233/3):
>
> This is my Java attempt on that positive number filter challenge: coffee “Program.java”: import java.util.Collection; import java.util.LinkedHashSet; public final class Program { @SafeVarargs static public final String[] filterArray(final String... strs) { if (strs == null || strs.length == 0) return new String[0]; final Collection\<String\> nums = new LinkedHashSet\<\>(); for (final String str : strs) try { Integer.parseUnsignedInt(str); nums.add(str); } c…

> <https://gist.github.com/GoToLoop/bba0c288aaeeb5ef9bb1>

---

<div class="post-metadata">

### Author: ![neilcsmith](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/neilcsmith/32/144_2.png) [@neilcsmith](https://discourse.processing.org/u/neilcsmith)
#### Post date: [December 16, 2020, 10:24am UTC](https://discourse.processing.org/t/using-the-try-catch/26108/11 "2020-12-16T10:24:56Z")

</div>

> [@GoToLoop](#):
>
> [NumberFormatException](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/NumberFormatException.html) is a very notable case where its `catch () {}` block works as an `if () {}` replacement:

Er, no, definitely not what I meant. Never use `try` in place of `if`. The core JDK libraries are a bit lacking here in the lack of a tryParse function, but just because they’re lacking doesn’t make it a good idea. And with Processing, use the internal parsing functions that at least handle the catch / hide the exception for you. Still slow though! There are (Java) libraries that can do this more efficiently.

OT - When I said “never” use for logic, I had in mind a couple of ways libraries I know have used exceptions to support things that _cannot_ otherwise be easily expressed. They will generally use their own exception classes too, to remove some of the things that make exception creation non-performant.
