Skip to content
GitLab
Menu
Projects
Groups
Snippets
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Sign in / Register
Toggle navigation
Menu
Open sidebar
Clark Lin
StudyCpp
Commits
71b234e2
Commit
71b234e2
authored
Nov 24, 2022
by
Administrator
Browse files
add exception handling
parent
a1d084a7
Changes
1
Show whitespace changes
Inline
Side-by-side
03.Advanced/ExceptionHandling.cpp
0 → 100644
View file @
71b234e2
#include <iostream>
using
namespace
std
;
class
MyException
:
public
exception
{
public:
const
char
*
what
()
const
throw
()
{
return
"C++ Exception"
;
}
};
int
main
()
{
double
devident
,
devisor
;
string
buff
;
cout
<<
"Input devident:"
<<
endl
;
cin
>>
devident
;
getline
(
cin
,
buff
);
cout
<<
"Input devisor:"
<<
endl
;
cin
>>
devisor
;
getline
(
cin
,
buff
);
// 显式地抛出异常
try
{
if
(
devisor
==
0
)
{
throw
"Devisor can NOT be 0!"
;
}
cout
<<
devident
<<
" / "
<<
devisor
<<
" = "
<<
devident
/
devisor
<<
endl
;
}
catch
(
const
char
*
msg
)
{
cout
<<
msg
<<
endl
;
}
// 隐式地抛出异常
string
s
=
"hello"
;
try
{
char
c
=
s
.
at
(
100
);
//拋出 out_of_range 异常
}
catch
(
out_of_range
&
e
)
{
cout
<<
e
.
what
()
<<
endl
;
}
// 显式地抛出自定义异常
try
{
throw
MyException
();
}
catch
(
MyException
&
e
)
{
cout
<<
e
.
what
()
<<
endl
;
}
}
\ No newline at end of file
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment