Java에서 일반적인 예외를 던지는 방법은 무엇입니까?
이 간단한 프로그램을 고려하십시오. 이 프로그램에는 두 개의 파일이 있습니다.
Vehicle.java:
class Vehicle {
private int speed = 0;
private int maxSpeed = 100;
public int getSpeed()
{
return speed;
}
public int getMaxSpeed()
{
return maxSpeed;
}
public void speedUp(int increment)
{
if(speed + increment > maxSpeed){
// throw exception
}else{
speed += increment;
}
}
public void speedDown(int decrement)
{
if(speed - decrement < 0){
// throw exception
}else{
speed -= decrement;
}
}
}
그리고 HelloWorld.java :
public class HelloWorld {
/**
* @param args
*/
public static void main(String[] args) {
Vehicle v1 = new Vehicle();
Vehicle v2 = new Vehicle();
// do something
// print something useful, TODO
System.out.println(v1.getSpeed());
}
}
첫 번째 클래스에서 볼 수 있듯이 예외를 throw하고 싶은 주석 ( "// throw exception")을 추가했습니다. 예외에 대해 고유 한 클래스를 정의해야합니까? 아니면 Java에 사용할 수있는 일반적인 예외 클래스가 있습니까?
고유 한 Exception 클래스를 만들 수 있습니다.
public class InvalidSpeedException extends Exception {
public InvalidSpeedException(String message){
super(message);
}
}
코드에서 :
throw new InvalidSpeedException("TOO HIGH");
IllegalArgumentException을 사용할 수 있습니다.
public void speedDown(int decrement)
{
if(speed - decrement < 0){
throw new IllegalArgumentException("Final speed can not be less than zero");
}else{
speed -= decrement;
}
}
던질 예외가 많이 있지만 예외를 던지는 방법은 다음과 같습니다.
throw new IllegalArgumentException("INVALID");
또한 예, 고유 한 사용자 지정 예외를 만들 수 있습니다.
편집 : 예외 사항에 대해서도 참고하십시오. 위와 같이 예외를 throw하고 예외를 포착하면 예외 String에서 제공 한에 액세스 할 수 있습니다 getMessage().
try{
methodThatThrowsException();
}catch(IllegalArgumentException e)
{
e.getMessage();
}
It really depends on what you want to do with that exception after you catch it. If you need to differentiate your exception then you have to create your custom Exception. Otherwise you could just throw new Exception("message goes here");
The simplest way to do it would be something like:
throw new java.lang.Exception();
However the following lines would be unreachable in your code. So, we have two ways:
- throw generic exception at the bottom of the method. \
- throw a custom exception in case you don't want to do 1.
Java has a large number of built-in exceptions for different scenarios.
In this case, you should throw an IllegalArgumentException, since the problem is that the caller passed a bad parameter.
You can define your own exception class extending java.lang.Exception (that's for checked exception - these which must be caught), or extending java.lang.RuntimeException - these exceptions does not have to be caught. The other solution is to review Java API and finding appropriate exception describing your situation: in this particular case I think that the best one would be IllegalArgumentException.
It depends, you can throw a more general exception, or a more specific exception. For simpler methods, more general exceptions are enough. If the method is complex, then, throwing a more specific exception will be reliable.
참고URL : https://stackoverflow.com/questions/6942624/how-to-throw-a-general-exception-in-java
'Nice programing' 카테고리의 다른 글
| 가장 가까운 5로 반올림 (0) | 2020.11.19 |
|---|---|
| 패턴과 일치하거나 빈 문자열 인 정규식 (0) | 2020.11.19 |
| 주어진 ID에 대해 Chrome 웹 스토어에서 CRX 파일을 다운로드하는 방법은 무엇입니까? (0) | 2020.11.19 |
| Android에서 이름으로 드로어 블 리소스에 액세스하는 방법 (0) | 2020.11.19 |
| 목록 이외의 유형에 대해 접기를 구성하는 것은 무엇입니까? (0) | 2020.11.19 |