Throw and throws in Java (#4990)

This commit is contained in:
Kacper
2018-08-19 22:02:27 +02:00
committed by maibin
parent a21e940d8c
commit 9156ec3736
10 changed files with 198 additions and 0 deletions
@@ -0,0 +1,15 @@
package com.baeldung.throwsexception;
public class Calculator {
public double divide(double a, double b) {
if (b == 0) {
throw new DivideByZeroException("Divider cannot be equal to zero!");
}
return a/b;
}
}
@@ -0,0 +1,9 @@
package com.baeldung.throwsexception;
public class DataAccessException extends RuntimeException {
public DataAccessException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,9 @@
package com.baeldung.throwsexception;
public class DivideByZeroException extends RuntimeException {
public DivideByZeroException(String message) {
super(message);
}
}
@@ -0,0 +1,41 @@
package com.baeldung.throwsexception;
import com.sun.mail.iap.ConnectionException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.SocketException;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
TryCatch tryCatch = new TryCatch();
try {
tryCatch.execute();
} catch (ConnectionException | SocketException ex) {
System.out.println("IOException");
} catch (Exception ex) {
System.out.println("General exception");
}
checkedException();
checkedExceptionWithThrows();
}
private static void checkedExceptionWithThrows() throws FileNotFoundException {
File file = new File("not_existing_file.txt");
FileInputStream stream = new FileInputStream(file);
}
private static void checkedException() {
File file = new File("not_existing_file.txt");
try {
FileInputStream stream = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,18 @@
package com.baeldung.throwsexception;
import javax.annotation.Nullable;
import java.sql.SQLException;
import java.util.List;
public class PersonRepository {
@Nullable
public String findNameById(String id) {
return id == null ? null : "example-name";
}
public List<String> findAll() throws SQLException {
throw new SQLException();
}
}
@@ -0,0 +1,22 @@
package com.baeldung.throwsexception;
import java.sql.SQLException;
public class SimpleService {
private PersonRepository personRepository = new PersonRepository();
public void wrappingException() {
try {
personRepository.findAll();
} catch (SQLException e) {
throw new DataAccessException("SQL Exception", e);
}
}
public void runtimeNullPointerException() {
String a = null;
a.length();
}
}
@@ -0,0 +1,13 @@
package com.baeldung.throwsexception;
import com.sun.mail.iap.ConnectionException;
import java.net.SocketException;
public class TryCatch {
public void execute() throws SocketException, ConnectionException, Exception {
//code that would throw any of: SocketException, ConnectionException, Exception
}
}