⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 5-3.txt

📁 java入门的几个代码,很实用,初学者不可错过
💻 TXT
字号:
import java.io.IOException;
public class ThrowException
{
public static void main(String args[])
{
try
{
String  s=getInput();   // getInput()  throw抛出异常
System.out.println(s);
}
catch(IOException e)   // 捕获异常
{
System.out.println(e.getMessage());
}
}
static String getInput() throws IOException   // getInput()方法抛出异常,由于在它的方法体中调用的其他方法抛出异常,并且该方法体本身使用throw抛出异常
{
char[] buffer =new char[20];
int counter = 0;
boolean flag =true;
while(flag)
{
buffer[counter] =(char)System.in.read();   // System.in.read()抛出异常。调用System.in.read()的方法要throws异常
if(buffer[counter]=='\n')
flag =false;
counter++;
if(counter>=20)
{
IOException ae =new IOException("buffer is full");//构造异常实例
throw ae;//抛出异常类的实例
}
}
return new String(buffer);
}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -