[BAEL-4990] Throwing exceptions in constructor

This commit is contained in:
Sarath 2021-07-08 17:31:45 +05:30
parent bd4beba1f0
commit d77187d33d
3 changed files with 92 additions and 0 deletions

View File

@ -0,0 +1,32 @@
package com.baeldung.constructors.exception;
import java.io.File;
import java.io.IOException;
public class Animal {
public Animal() throws InstantiationException {
throw new InstantiationException("Cannot be instantiated");
}
public Animal(String id, int age) {
if (id == null)
throw new NullPointerException("Id cannot be null");
if (age < 0)
throw new IllegalArgumentException("Age cannot be negative");
}
public Animal(File file) throws SecurityException, IOException {
// Avoiding Path traversal attacks
if (file.isAbsolute()) {
throw new SecurityException("Traversal attack - absolute path not allowed");
}
// Avoiding directory traversal
// a/../..b/
if (!file.getCanonicalPath()
.equals(file.getAbsolutePath())) {
throw new SecurityException("Directory traversal attempt?");
}
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.constructors.exception;
public class Bird extends Animal {
// Note that we are throwing parent exception
public Bird() throws ReflectiveOperationException {
super();
}
public Bird(String id, int age) {
super(id, age);
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.constructors.exception;
import java.io.File;
import org.assertj.core.api.Assertions;
import org.junit.Test;
public class AnimalUnitTest {
@Test
public void givenNoArgument_thenFails() {
Assertions.assertThatThrownBy(() -> {
new Animal();
})
.isInstanceOf(Exception.class);
}
@Test
public void givenInvalidArg_thenFails() {
Assertions.assertThatThrownBy(() -> {
new Animal(null, 30);
})
.isInstanceOf(NullPointerException.class);
}
@Test(expected = Test.None.class)
public void givenValidArg_thenSuccess() {
new Animal("1234", 30);
}
@Test
public void givenAbsolutePath_thenFails() {
Assertions.assertThatThrownBy(() -> {
new Animal(new File("temp.txt").getAbsoluteFile());
})
.isInstanceOf(SecurityException.class);
}
@Test
public void givenDirectoryTraversalPath_thenFails() {
Assertions.assertThatThrownBy(() -> {
new Animal(new File(File.separator + ".." + File.separator + "temp.txt"));
})
.isInstanceOf(SecurityException.class);
}
}