104 lines
5.6 KiB
Markdown
104 lines
5.6 KiB
Markdown
---
|
||
title: "Java: Because of a Question About try-catch, I Failed My Interview…"
|
||
source: "https://medium.com/javarevisited/java-because-i-didnt-know-whether-the-try-catch-block-should-be-placed-outside-or-inside-the-for-50de407dcf63"
|
||
author:
|
||
- "[[Dylan Smith]]"
|
||
published: 2024-09-09
|
||
created: 2024-10-29
|
||
description: "Today, let’s talk about a relatively light topic. A friend was reprimanded by an interviewer some time ago. Because when my friend was preparing for the interview, he was preparing some relatively…"
|
||
tags:
|
||
- "clippings"
|
||
---
|
||
Today, let’s talk about a relatively light topic. A friend was reprimanded by an interviewer some time ago. Because when my friend was preparing for the interview, he was preparing some relatively complex system interview questions and principle questions. As a result, the interviewer suddenly came up with a simple question:
|
||
|
||
> ***Should try-catch be written inside or outside the for loop? And state your reasons.***
|
||
|
||
For a moment, my friend didn’t know what this question was asking, so he casually answered that he habitually placed it outside the for loop because it looked more beautiful.
|
||
|
||
But this left a bad impression on the interviewer and also laid the groundwork for the subsequent interview failure…😔
|
||
|
||

|
||
|
||
Photo by [Walls.io](https://unsplash.com/@walls_io?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com/?utm_source=medium&utm_medium=referral)
|
||
|
||
In fact, the answer to this question is not that it is always better to put it inside or outside, or that it is bad. This needs to be answered in combination with specific usage scenarios.
|
||
|
||
## 1\. Usage Scenarios
|
||
|
||
Since putting try-catch outside or inside the for loop has different effects if an exception occurs.
|
||
|
||
So it needs to be considered in combination with specific business scenarios.
|
||
|
||
## ① Putting try-catch outside the for loop
|
||
|
||
Code example:
|
||
|
||
```
|
||
public static void outside() { try { for (int count = 1; count <= 4; count++) { if (count == 3) { int num = count / 0; } else { System.out.println("success, count:" + count); } } } catch (Exception e) { System.out.println("An exception occurs."); } }
|
||
```
|
||
|
||
Output:
|
||
|
||
```
|
||
success, count:1success, count:2An exception occurs.
|
||
```
|
||
|
||
Obviously, when try-catch is placed outside the for loop, if an exception occurs during the for loop, then the for loop will be terminated.
|
||
|
||
## ② Putting try-catch inside the for loop
|
||
|
||
Code example:
|
||
|
||
```
|
||
public static void tryInside() { for (int count = 1; count <= 4; count++) { try { if (count == 3) { int num = count / 0; } else { System.out.println("success, count:" + count); } } catch (Exception e) { System.out.println("An exception occurs."); } } }
|
||
```
|
||
|
||
Output:
|
||
|
||
```
|
||
success, count:1success, count:2An exception occurs.success, count:4
|
||
```
|
||
|
||
When try-catch is inside the for loop, if an exception occurs during the for loop, the exception is caught by catch and does not affect the continuation of the for loop.
|
||
|
||
If…during an interview, if you really didn’t even get the usage effects of being outside or inside as mentioned above correct, then, really, you can wait for notification.
|
||
|
||
Next, let’s discuss the differences in performance.
|
||
|
||
## 2\. Performance
|
||
|
||
In terms of time, there is actually no difference.
|
||
|
||
In terms of memory usage, if there is no exception, there is also no difference.
|
||
|
||
But if an exception occurs, then pay attention.
|
||
|
||
What needs to be paid attention to? Look at the following code:
|
||
|
||
```
|
||
public class TryCatchDemo { public static void main(String[] args) { Runtime runtime = Runtime.getRuntime(); long startMemory = runtime.totalMemory() - runtime.freeMemory(); for (int i = 0; i < 100000; i++) { try { if (i > 2) { int num = i / 0; } else { System.out.println("success, i:" + i); } } catch (Exception e) { System.out.println("An exception occurs."); } } long endMemory = runtime.totalMemory() - runtime.freeMemory(); long memoryUsed = endMemory - startMemory; System.out.println("memoryUsed: " + memoryUsed + " byte"); }}
|
||
```
|
||
|
||
Output:
|
||
|
||

|
||
|
||
As can be seen, when try-catch is placed inside the for loop, since an exception does not terminate the for loop. So if there is really a scenario where a large number of business processes will all have exceptions, it will consume a lot of memory in a short time.
|
||
|
||
If there are not many code errors, there is almost no difference between putting try-catch inside and outside the for loop.
|
||
|
||
**Finally, I want to say that interview preparation must not ignore basic knowledge. Only by laying a solid foundation can one handle more complex and profound problems with ease.**
|
||
|
||
The above is all the content shared this time! **If the article was helpful, please clap 👏and follow, thank you! ╰(\*°▽°\*)╯\***\*
|
||
|
||
**I’m Dylan, looking forward to progressing with you. ❤️**
|
||
|
||
Recommend reading.
|
||
|
||

|
||
|
||
## Java Interview and Usage Skills.
|
||
|
||

|
||
|
||
## Mastering Redis And Cache |