Added the code for "Errors and Exceptions in Java". (#13104)

* Added the code for "Errors and Exceptions in Java".

* Added the unit tests.
This commit is contained in:
Arya 2022-11-30 23:21:46 +03:30 committed by GitHub
parent 21c42ebebc
commit c22f091771
5 changed files with 66 additions and 0 deletions

View File

@ -0,0 +1,15 @@
package com.baeldung.exception.exceptions_vs_errors;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class CheckedExceptionExcample {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream(new File("test.txt"))) {
fis.read();
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.exception.exceptions_vs_errors;
public class ErrorExample {
public static void main(String[] args) {
overflow();
}
public static void overflow() {
System.out.println("overflow...");
overflow();
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.exception.exceptions_vs_errors;
public class RuntimeExceptionExample {
public static void main(String[] args) {
int[] arr = new int[20];
arr[20] = 20;
System.out.println(arr[20]);
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.exception.exceptions_vs_errors;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
// Unit test for the ErrorExample class.
public class ErrorExampleUnitTest {
@Test
public void whenMainMethodIsRun_thenStackOverflowError() {
Assertions.assertThrows(StackOverflowError.class,
() -> ErrorExample.main(null));
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.exception.exceptions_vs_errors;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
// Unit test for the RuntimeExceptionExample class.
public class RuntimeExceptionExampleUnitTest {
@Test
public void whenMainMethodIsRun_thenArrayIndexOutOfBoundsExceptionIsThrown() {
Assertions.assertThrows(ArrayIndexOutOfBoundsException.class,
() -> RuntimeExceptionExample.main(null));
}
}