Java中跳转结构
在Java中,跳转结构用于控制程序的执行流程。
2.4.1 break
- 用途: 用于终止当前循环(
for
、while
、do-while
)或switch
语句。
public class BreakExample {public static void main(String[] args) {for (int i = 0; i < 10; i++) {if (i == 5) {break; // 当i等于5时,终止循环}System.out.println(i);}}
}
2.4.2 continue
- 用途: 用于跳过当前循环的剩余部分,直接进入下一次循环。
public class ContinueExample {public static void main(String[] args) {for (int i = 0; i < 10; i++) {if (i % 2 == 0) {continue; // 跳过偶数,继续下一次循环}System.out.println(i);}}
}
2.4.3 return
- 用途: 用于从方法中返回值并终止方法的执行。如果方法没有返回值(
void
),则仅用于终止方法。
public int add(int a, int b) {return a + b; // 返回a和b的和,并终止方法
}
2.4.4 throw
- 用途: 用于手动抛出一个异常。
public void checkAge(int age) {if (age < 0) {throw new IllegalArgumentException("Age cannot be negative");}
}
2.4.5 try-catch-finally
- 用途: 用于异常处理。
try
块中包含可能抛出异常的代码,catch
块用于捕获并处理异常,finally
块用于执行无论是否发生异常都必须执行的代码。
public class TryCatchFinallyExample {public static void main(String[] args) {try {int result = 10 / 0; // 可能会抛出ArithmeticException} catch (ArithmeticException e) {System.out.println("Caught exception: " + e.getMessage());} finally {System.out.println("Finally block executed");}}
}
2.4.6 assert
- 用途: 用于调试时检查某个条件是否为真。如果条件为假,则抛出
AssertionError
。
public class TestAssert {@Testpublic void testAssertFalse() {int x = 10;assert x > 20 : "x should be greater than 0";}
}