[英]Try Catch Block in Java
所以我給了這個代碼,我必須創建一個Exception,然后使用Try/Catch
Block來捕獲它。 我已經在代碼的底部制作了Exception。 但我以前從未使用過Try/Catch
Block,也不確定如何實現它。
例外情況是輸入未在enum
下列出的等級。 我也需要使用帶有捕獲異常的toString
,但我很確定我可以解決這個問題。
package pracapp4;
import java.util.Scanner;
public class Staff extends Employee
{
enum Title
{
DEPARTMENT_HEAD, DIRECTOR, DEAN, VICE_CHANCELLOR, CHANCELLOR
}
private Title title;
public Staff()
{
super();
title = Title.DEPARTMENT_HEAD;
}
public Staff(String firstName, String lastName, int salary, Title title)
{
super(firstName, lastName, salary);
this.title = title;
}
@Override
public String toString()
{
return super.toString() + "\n\tTitle: " + title;
}
@Override
public void display()
{
System.out.println("<<Staff>>" + this);
}
@Override
public void input(Scanner in)
{
super.input(in);
if (in.hasNext())
{
this.title = Enum.valueOf(Title.class, in.next());
}
}
class InvalidRankException extends Exception
{
public InvalidRankException()
{
super ("Unknown Rank Name: ");
}
}
}
你不需要那個例外。 當你將Title枚舉添加為傳遞給Staff構造函數的類型時,就不可能提供不在枚舉中的值。 你永遠不會得到無效的頭銜。 這就是枚舉的全部要點。
更新:一個小代碼審查是這里的一個訂單。
try / catch用於捕獲try子句中方法拋出的異常。 如果try中的方法沒有拋出任何異常,那么try / catch就沒有意義了。 現在你做了你的異常,但是沒有拋出你的異常的方法。
這是關於如何使用異常的簡單示例:
public class myTest
{
public void myMethod() throws InvalidRankException
{
//Logic here
if(something_is_wrong)
{
throw new InvalidRankException("Invalid Rank on myMethod due ...");
}
}
class InvalidRankException extends Exception
{
public InvalidRankException()
{
super ("Unknown Rank Name: ");
}
}
現在,無論何時運行MyTest.myMethod(),編譯器都需要圍繞該調用的try / catch。
MyTest test = new MyTest();
try
{
test.myMethod();
}
catch(InvalidRankException ex)
{
//Something went wrong
}
不完全確定你要做什么,但try-catch塊的工作方式如下:
try{
throw new Exception("Example exception");
}
catch(Exception e){
System.out.println( "Exception caught: " + e.getMessage() );
}
您還必須修改您正在嘗試的方法,以便它拋出您正在尋找的Exception:
public void doSomething(String blah) throws Exception
捕獲異常非常簡單:
try{
//Some code that throws MyExceptionClass
}catch(MyException e){
//Some code that handles the exception e
}
拋出異常很簡單:
throw new MyException(some, parameters, of, your choice);
如果您的異常不是從RuntimeException下降,那么您必須聲明該方法拋出它:
public void myExceptionCausingMethod() throws MyException{
//Method code
}
try / catch語句包含一些代碼,用於處理該代碼中可能出現的錯誤和異常。
public void input(Scanner in) throws InvalidRankException {
super.input(in);
if (in.hasNext()) {
try {
title = Enum.valueOf(Title.class, in.next());
} catch(InvalidRankException ire) {
//You've hit the exception, code in here how to handle the situation
}
}
}
這里有兩個問題:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.