Surround code fragments
IntelliJ IDEA provides standard templates for surrounding code fragments with various constructs based on the language of the source code. This includes if...else
conditional statements, do...while
and for
loops, combinations of try...catch...finally
, XML tags, folding regions, and other constructs.
Select a code fragment.
Press CtrlAlt0T or go to Code | Surround With in the main menu.
Alternatively, on the toolbar that appears, click Surround.
Select the necessary surround statement from the list. When you hover over an option, you will see a preview of the change that will be applied if you select that statement.
You can edit code templates that are used in the surround statements. In the Settings dialog (CtrlAlt0S) , go to Editor | File and Code Templates.
For example, you can configure final modifier, name or even a type of the exception for the try...catch
conditional statement.
note
If live templates contain the $SELECTION$ variable, they can be used as surround statements.
To create your own surround statement, create a live template and use the
$SELECTION$
variable in the template text.
In the following example, we select the int number = scanner.nextInt();
Java statement and apply the try / catch surround statement to it.
Before
import java.util.Scanner;public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); int number = scanner.nextInt(); System.out.println("You entered: " + number); }}
After
import java.util.Scanner;public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); int number = 0; try { number = scanner.nextInt(); } catch (Exception e) { throw new RuntimeException(e); } System.out.println("You entered: " + number); }}
This feature applies to the following languages (contexts):
Context | Surround with |
---|---|
Java statements |
|
Java expressions |
|
XML/HTML /JSP/JSPX tags |
|
JavaScript statements |
|
PHP statements |
|
Custom folding region comments | Any fragment of code, where Surround With is applicable. |
Thanks for your feedback!